/*******************************************************************/
/*																   */
/*							UTILS								   */
/*																   */
/*******************************************************************/

var click_checkbox = 0;
var firme_indici = []; // aici tin indicii pentru firme
var comenzi_indici = []; //aici tin indicii pentru comenzi

var sume_sol = [];
var sume_exec = [];
var monede = ['EUR', 'RON', 'USD'];

var CT_PRET_ABON_TIP_1 = 247;
var CT_PRET_ABON_TIP_2 = 428;
var CT_PRET_ABON_TIP_3 = 644;
var CT_DASHBOARD_MARFA = 0;

function print_error_message(message) {
	alert(message);
}

function add_new_user() {
	if (check_users_number()) 
        arata_modal_user();
    else
        alert(LANG_Aveti_numarul_maxim_de_useri);	
}

function edit_adresa(tip, tip_loc, index, id_rezultat) {
	//in caz ca avem adrese de genul incarcare descarcare parametrul index va desemna a cata adresa din sir este :D
	sndReqNew('modal_add_adresa.php','tip='+tip+'&tip_loc='+tip_loc+'&index='+index+'&id_rezultat='+id_rezultat, '', 'displayMessage(response);', 0);
}

function sterge_adresa(tip, tip_loc, index, id_rezultat) {
	//in caz ca avem adrese de genul incarcare descarcare parametrul index va desemna a cata adresa din sir este :D
	if (confirm(LANG_Vreti_sa_stergeti_adresa)) {
		sndReqNew('AJAX_proxy.php','f=sterge_adresa&tip='+tip+'&tip_loc='+tip_loc+'&index='+index+'&id_rezultat='+id_rezultat, id_rezultat, '', 0);	
	}
}

function edit_cont(index, tip_cont) {	
	sndReqNew('modal_add_cont_firma.php','index='+index+'&tip_cont='+tip_cont,'', 'displayMessage(response);', 0);
}

function edit_ruta_firma(index) {
	sndReqNew('modal_add_rute_firma.php','index='+index,'', 'displayMessage(response); document.getElementById(\'rute_loc1\').focus();', 0);
}

function sterge_ruta_firma(index) {
	if (confirm(LANG_Vreti_sa_stergeti_ruta)) {
		sndReqNew('AJAX_proxy.php','f=sterge_rute_firme&index='+index, 'td_rute_firme', '', 0);	
	}
}

function new_cont_confirm(optiune, index, tip_cont) {
    var cont = document.getElementById("cont").value;
	var moneda = document.getElementById("moneda").value;
	var banca = document.getElementById("banca").value;
	var sucursala = document.getElementById("sucursala").value;
	
    // Fa campurile albe din nou  
    document.getElementById('td_cont').className = '';
    document.getElementById('td_moneda').className = '';
    document.getElementById('td_banca').className = '';
    document.getElementById('td_sucursala').className = '';
	//submit the data to the server
	
	sndReqNew('AJAX_proxy.php','f=ajax_create_new_cont&optiune='+optiune+'&index='+index+'&cont='+cont+'&moneda='+moneda+'&banca='+banca+'&sucursala='+sucursala+'&tip_cont='+tip_cont, 'td_conturi'
            , 'closeMessage(); sndReqNew(\'AJAX_proxy.php\', \'f=render_cont_table&tip_cont='+tip_cont+'\', id, \'\', 0);', 0);	  
}

function new_ruta_firma_confirm(optiune, index) {
    var loc1 = document.getElementById("rute_loc1").value;
	var loc2 = document.getElementById("rute_loc2").value;
	
    // Fa campurile albe din nou  
    document.getElementById('td_loc1').className = '';
    document.getElementById('td_loc2').className = '';    
	//submit the data to the server
	
	sndReqNew('AJAX_proxy.php','f=ajax_create_new_ruta&optiune='+optiune+'&index='+index+'&loc1='+loc1+'&loc2='+loc2, 'td_rute_firme'
            , 'closeMessage(); sndReqNew(\'AJAX_proxy.php\', \'f=render_rute_table\', id, \'\', 0);', 0);
}

function new_contact_confirm(optiune, index) {
	
	var contact_name = document.getElementById("contact_nume").value;
	var contact_sex = document.getElementById("contact_sex").value;
	var contact_functie = document.getElementById("contact_functie").value;
	var contact_tel_fix = document.getElementById("contact_tel_fix").value;
	var contact_tel_fax = document.getElementById("contact_tel_fax").value;
	var contact_tel_mobil = document.getElementById("contact_tel_mobil").value;
	var contact_email = document.getElementById("contact_email").value;
	
    // Fa campurile albe din nou
    document.getElementById('td_contact_nume').className = '';
    document.getElementById('td_contact_sex').className = '';
    document.getElementById('td_contact_functie').className = '';
    document.getElementById('td_contact_tel_fix').className = '';
    document.getElementById('td_contact_tel_fax').className = '';
    document.getElementById('td_contact_tel_mobil').className = '';
    document.getElementById('td_contact_email').className = '';
	//submit the data to the server   
	
	sndReqNew('AJAX_proxy.php','f=ajax_create_new_contact&optiune='+optiune+'&index='+index+'&contact_name='+contact_name+'&contact_sex='+contact_sex+'&contact_functie='+contact_functie+'&contact_tel_fax='+contact_tel_fax+'&contact_tel_fix='+contact_tel_fix+'&contact_tel_mobil='+contact_tel_mobil+'&contact_email='+contact_email, 'td_contacte'
    , 'closeMessage(); sndReqNew(\'AJAX_proxy.php\', \'f=render_contact_table\', \'td_contacte\', \'\', 0)', 0);
}

function new_dashboard_confirm(tip, optiune, index) {
	
	var tara_plecare = document.getElementById("tara_plecare").value;
	var oras_plecare = document.getElementById("oras_plecare").value;
	
	var data_plecare = document.getElementById("data_plecare").value;	
	var tara_sosire = document.getElementById("tara_sosire").value;
	var oras_sosire = document.getElementById("oras_sosire").value;
	var data_sosire = document.getElementById("data_sosire").value;	
	var comentariu = document.getElementById("comentariu").value;

    var pret = document.getElementById("pret").value;
	var moneda = document.getElementById("moneda").value;
	var km = document.getElementById("km").value;	

    // Fa campurile albe din nou
    document.getElementById('td_tara_plecare').className = '';
    document.getElementById('td_oras_plecare').className = '';
    document.getElementById('td_data_plecare').className = '';
    document.getElementById('td_tara_sosire').className = '';
    document.getElementById('td_oras_sosire').className = '';
    document.getElementById('td_data_sosire').className = '';
    document.getElementById('td_comentariu').className = '';
    
    document.getElementById('td_pret').className = '';
    document.getElementById('td_moneda').className = '';
    document.getElementById('td_km').className = '';        
	//submit the data to the server   
	
	if (tip == CT_DASHBOARD_MARFA) 
		var td_id = 'dash_marfa'
	else
		var td_id = 'dash_camion';

	sndReqNew('AJAX_proxy.php','f=ajax_create_new_dash&tip='+tip+'&optiune='+optiune+'&index='+index
    +'&pret='+pret+'&moneda='+moneda+'&km='+km+'&tara_plecare='+tara_plecare+'&oras_plecare='+oras_plecare+'&data_plecare='+data_plecare
    +'&tara_sosire='+tara_sosire+'&oras_sosire='+oras_sosire+'&data_sosire='+data_sosire+'&comentariu='+comentariu, ''
    , 'closeMessage(); sndReqNew(\'AJAX_proxy.php\', \'f=render_dasboard&tip='+tip+'&optiune='+optiune+'&index='+index+'\', \''+td_id+'\', \'\', 0)', 0);

} 

function new_adresa_confirm(tip, tip_loc, id_rezultat, optiune, index, adrRequired) {
	
	//index in caz ca vreau sa editez o adresa     
	var adresa = document.getElementById("adresa").value;
	var oras = document.getElementById("oras").value;
	var judet = document.getElementById("judet").value;
    var cod_postal = document.getElementById("cod_postal").value;
    var tara = document.getElementById("tara").value;
    var nume_firma = document.getElementById("nume_firma").value;
    var nume_contact = document.getElementById("nume_contact").value;
    var tel_contact = document.getElementById("tel_contact").value;
    var alte_mentiuni = document.getElementById("alte_mentiuni").value;
    
    // Campuri pt incarcare/descarcare
    var data = '';
    var data_efectiva = '';    
    var tip_marfa = '';
    var nr_colete = '';
    var greutate = '';
    // Campuri pentru import/export
    var nume_birou_vamal = '';
	var cod_vama = '';	
    var impexp = '';
	var legatura_incarcare = '';
    var nr = '';
    var i,temp;
        
    // Daca e adresa de descarcare fac submit la legaturi
    if (tip_loc != 0) {
        nr = document.getElementById("number_of_incarcari").innerHTML;
        for (i=1; i<= nr; i++) {
            temp = 'loc'+i;
            if (document.getElementById(temp).checked == true)
                legatura_incarcare += document.getElementById(temp).value + ';';
        }
    }
    // Daca e adresa de incarcare / descarcare
    if (tip_loc < 2) {
        data = document.getElementById("data").value;
        data_efectiva = document.getElementById("data_efectiva").value;    
        tip_marfa = document.getElementById("tip_marfa").value;
        nr_colete = document.getElementById("nr_colete").value;
        greutate = document.getElementById("greutate").value;
    }
    else {
        // Daca e adresa de vama import / export
        impexp = document.getElementById("impexp").value;
        nume_birou_vamal = document.getElementById("nume_birou_vamal").value;
        cod_vama = document.getElementById("cod_vama").value 
    }        
    
    // Fa campurile albe din nou
    document.getElementById('td_adresa').className = '';
    document.getElementById('td_oras').className = '';
    document.getElementById('td_judet').className = '';
    document.getElementById('td_cod_postal').className = '';
    document.getElementById('td_tara').className = '';
    document.getElementById('td_nume_firma').className = '';  
      
    // Daca e adresa de incarcare / descarcare
    if (tip_loc < 2) {
        document.getElementById('td_data').className = '';
        document.getElementById('td_data_efectiva').className = '';
        document.getElementById('td_tip_marfa').className = '';
        document.getElementById('td_nr_colete').className = '';
        document.getElementById('td_greutate').className = '';
        
        sndReqNew('AJAX_proxy.php','f=ajax_create_new_adresa&optiune='+optiune+'&tip='+tip+'&tip_loc='+tip_loc
        +'&data='+data+'&data_efectiva='+data_efectiva+'&tip_marfa='+tip_marfa+'&nr_colete='+nr_colete+'&greutate='+greutate
        +'&nume_contact='+nume_contact+'&tel_contact='+tel_contact+'&alte_mentiuni='+alte_mentiuni
        +'&adresa='+adresa+'&oras='+oras+'&judet='+judet+'&cod_postal='+cod_postal+'&nume_firma='+nume_firma
        +'&tara='+tara+'&index='+index+'&adrRequired='+adrRequired+'&legatura_incarcare='+legatura_incarcare, id_rezultat
        , 'closeMessage(); sndReqNew(\'AJAX_proxy.php\', \'f=render_adresa&tip='+tip+'&tip_loc='+tip_loc+'&id_rezultat='+id_rezultat+'\',id, \'\', 0)', 0);
    }
    else {
        // Daca e adresa de vama import / export
        document.getElementById('td_impexp').className = '';   
        document.getElementById('td_nume_birou_vamal').className = '';   
        document.getElementById('td_cod_vama').className = '';   
        
        sndReqNew('AJAX_proxy.php','f=ajax_create_new_adresa&optiune='+optiune+'&tip='+tip+'&tip_loc='+tip_loc
        +'&nume_contact='+nume_contact+'&tel_contact='+tel_contact+'&alte_mentiuni='+alte_mentiuni
        +'&nume_birou_vamal='+nume_birou_vamal+'&cod_vama='+cod_vama
        +'&adresa='+adresa+'&oras='+oras+'&judet='+judet+'&cod_postal='+cod_postal+'&nume_firma='+nume_firma
        +'&tara='+tara+'&impexp='+impexp+'&index='+index+'&adrRequired='+adrRequired+'&legatura_incarcare='+legatura_incarcare, id_rezultat
        , 'closeMessage(); sndReqNew(\'AJAX_proxy.php\', \'f=render_adresa&tip='+tip+'&tip_loc='+tip_loc+'&id_rezultat='+id_rezultat+'\',id, \'\', 0)', 0);
    }
		
}

function sterge_contact(index) {	
	if (confirm(LANG_Vreti_sa_stergeti_contactul)) {
		sndReqNew('AJAX_proxy.php','f=sterge_contact&index='+index, 'td_contacte', '', 0);	
        //sndReqNew(\'AJAX_proxy.php\', \'f=render_contact_table\', \'td_contacte\', \'\', 0)
	}
}

function sterge_cont(index, tip_cont) {
	if (confirm(LANG_Vreti_sa_stergeti_contul)) {
		sndReqNew('AJAX_proxy.php', 'f=sterge_cont&index='+index+'&tip_cont='+tip_cont, 'td_conturi', '', 0);	
	}
}

function arata_modal_contact() {
	sndReqNew('modal_add_contact_firma.php','','', 'displayMessage(response); document.getElementById(\'contact_nume\').focus();', 0);
}

function arata_modal_rute() {
	sndReqNew('modal_add_rute_firma.php','','', 'displayMessage(response); document.getElementById(\'rute_loc1\').focus();', 0);
}

function edit_contact(index) {
	sndReqNew('modal_add_contact_firma.php','index='+index,'', 'displayMessage(response);', 0);
}

function arata_modal_cont(tip_cont) {
	sndReqNew('modal_add_cont_firma.php','tip_cont='+tip_cont,'', 'displayMessage(response); document.getElementById(\'cont\').focus();', 0);
}

function arata_contacte_comanda(id_firma, id_unde) {
	if (id_firma == -1) {
		if (id_unde == 'contact_sol') {
			var contact_sel = document.getElementById("id_firma_sol");
			id_firma = contact_sel.options[contact_sel.selectedIndex].value;		
			sndReqNew('AJAX_proxy.php','nume_unde='+id_unde+'&f=arata_contact_comanda&id_firma='+id_firma, id_unde, 'seteazaHidden();', 0);
		}
		if (id_unde == 'contact_exec') {
			var contact_sel = document.getElementById("id_firma_exec");
			id_firma = contact_sel.options[contact_sel.selectedIndex].value;		
			sndReqNew('AJAX_proxy.php','nume_unde='+id_unde+'&f=arata_contact_comanda&id_firma='+id_firma, id_unde, 'seteazaHidden();', 0);
		}		
	}
	else
		sndReqNew('AJAX_proxy.php','nume_unde='+id_unde+'&f=arata_contact_comanda&id_firma='+id_firma, id_unde, 'seteazaHidden();', 0);
}

function arata_modal_adresa(id_rezultat, tip, tip_loc, adrRequired) {
	
	//id_rezultat este locul unde se va arata adresa
	//tip este tipul de adresa corespunzator 0 - Client; 1 - Firma; 2 - Comanda
    //tip_loc este tipul de adresa 0 - incarcare; 1 - descarcare; 2 - vama import; 3 - vama export
	//ardRequired - true / false
	
    if (tip_loc == 2 || tip_loc == 3)
        inaltime = 325;
    else
        inaltime = 290;    
	sndReqNew('modal_add_adresa.php','id_rezultat='+id_rezultat+'&tip='+tip+'&tip_loc='+tip_loc+'&adrRequired='+adrRequired
            ,'', 'displayMessage(response); document.getElementById(\'adresa\').focus();', 0);
}

function arata_firme_pag(pagina, per_pag, id_rezultat, id_client, keyword, camp, order, camp_order, tip_firma) {
	remove_by_ID('notice_msg');
	sndReqNew('AJAX_proxy.php', 'f=render_firme&camp_order='+camp_order+'&tip_firma='+tip_firma+'&id_client='+id_client+'&pagina='+pagina+'&per_pag='+per_pag+'&keyword='+keyword+'&camp='+camp+'&order='+order, id_rezultat, '', 0);
}

function arata_comenzi_pag(pagina, per_pag, id_rezultat, id_client, comanda_incasata, comanda_platita, scadenta_incasare, scadenta_plata, f_sol, f_exec, keyword, val1, val2, camp, order, pret_min, pret_max, cost_min, cost_max, data_scadenta_sol1, data_scadenta_sol2, data_scadenta_exec1, data_scadenta_exec2, data_factura_sol1, data_factura_sol2, data_factura_exec1, data_factura_exec2, sc_incasare, sc_plata, cond_firme, camp_sort) {
	document.getElementById('status_plata').innerHTML = LANG_Total_suma_solicitant + "<br />" + LANG_Total_suma_executant;
	comenzi_indici.length = 0;
	comenzi_indici = [];
	remove_by_ID('notice_msg');  	
	sndReqNew('AJAX_proxy.php', 'f=render_comenzi&id_client='+id_client+'&per_pag='+per_pag+'&pagina='+pagina+'&comanda_incasata='+comanda_incasata+'&comanda_platita='+comanda_platita+'&scadenta_incasare='+scadenta_incasare+'&scadenta_plata='+scadenta_plata+'&f_sol='+f_sol+'&f_exec='+f_exec+'&camp='+camp+'&order='+order+'&keyword='+keyword+'&val1='+val1+'&val2='+val2+'&pret_min='+pret_min+'&f_sol='+f_sol+'&f_exec='+f_exec+'&pret_max='+pret_max+'&cost_min='+cost_min+'&cost_max='+cost_max+'&data_scadenta_sol1='+data_scadenta_sol1+'&data_scadenta_sol2='+data_scadenta_sol2+'&data_scadenta_exec1='+data_scadenta_exec1+'&data_scadenta_exec2='+data_scadenta_exec2+'&data_factura_sol1='+data_factura_sol1+'&data_factura_sol2='+data_factura_sol2+'&data_factura_exec1='+data_factura_exec1+'&data_factura_exec2='+data_factura_exec2+'&sc_incasare='+sc_incasare+'&sc_plata='+sc_plata+'&cond_firme='+cond_firme+'&camp_sort='+camp_sort, id_rezultat, '', 1);
}

function show_firme(id_rezultat, pagina) {	
	//preiau informatiile din formul de filtrare
	remove_by_ID('notice_msg');
	var tip_firma_sel = document.getElementById("tip_firma");	
	var tip_firma = tip_firma_sel.options[tip_firma_sel.selectedIndex].value;
	
	//preiau informatiile din formul de cautare
	
	var camp_order = document.getElementById("camp_order").value;
	
	var camp_sel = document.getElementById("camp_search");
	var camp = camp_sel.options[camp_sel.selectedIndex].value;
	var val1 = '';
	var val2 = '';
	
	if (camp != '1rute')
		var keyword = document.getElementById("keyword_kk").value;		
	else {
		//inseamna ca a fost selectat un camp de cautare cu valori intre 2 valori date de user...gen rute
		var val1 = document.getElementById("val1").value;
		var val2 = document.getElementById("val2").value;
	}
		
	//preiau cate pe pagina
	var per_page_sel = document.getElementById("per_page");
	var per_pagina = per_page_sel.options[per_page_sel.selectedIndex].value;
	var order = 'ASC';  

	sndReqNew('AJAX_proxy.php', 'f=update_profile&camp=firme_per_pag&value='+per_pagina, '', 'show_firme_rest('+tip_firma+", '"+camp_order+"', '"+order+"', "+ per_pagina+',' + pagina + ",'" + camp + "','" + keyword+"','"+ id_rezultat+"','"+ val1+"','"+ val2+"');", 1);	
}

function show_firme_rest(tip_firma, camp_order, order, per_pagina,pagina, camp, keyword, id_rezultat, val1, val2) {
	
	sndReqNew('AJAX_proxy.php', 'f=render_firme&camp_order=nume&tip_firma='+tip_firma+'&per_pag='+per_pagina+'&pagina='+pagina+'&order='+order+'&camp='+camp+'&keyword='+keyword+'&val1='+val1+'&val2='+val2, id_rezultat, '', 1)	
}

function show_comenzi(id_rezultat, pagina) {
	remove_by_ID('notice_msg');
    comenzi_indici.length = 0;
    comenzi_indici = []; 
    
	var comanda_incasata_sel = document.getElementById("incasata_sel");
	var comanda_incasata = comanda_incasata_sel.options[comanda_incasata_sel.selectedIndex].value;	
	
	var comanda_platita_sel = document.getElementById("platita_sel");
	var comanda_platita = comanda_platita_sel.options[comanda_platita_sel.selectedIndex].value;	
	
	var scadenta_incasare_sel = document.getElementById("sc_incasare_sel");
	var scadenta_incasare = scadenta_incasare_sel.options[scadenta_incasare_sel.selectedIndex].value;	
	
	var scadenta_plata_sel = document.getElementById("sc_plata_sel");
	var scadenta_plata = scadenta_plata_sel.options[scadenta_plata_sel.selectedIndex].value;	
	
	var f_sol_sel = document.getElementById("f_sol_sel");
	var f_sol = f_sol_sel.options[f_sol_sel.selectedIndex].value;	
	
	var sau_si_sel = document.getElementById("sau_si");
	var sau_si = sau_si_sel.options[sau_si_sel.selectedIndex].value;
	
	var f_exec_sel = document.getElementById("f_exec_sel");
	var f_exec = f_exec_sel.options[f_exec_sel.selectedIndex].value;	
	
	//preiau informatiile din formul de cautare
	var spancontainer = document.getElementById('campuri');

	if (spancontainer.innerHTML.length < 100) {
		var keyword = document.getElementById("keyword").value;
	}
	else {
		var val1 = document.getElementById("val1").value;
		var val2 = document.getElementById("val2").value;
	}	
		
	var camp_sel = document.getElementById("camp_sel");
	var camp = camp_sel.options[camp_sel.selectedIndex].value;
	
	//preiau cate pe pagina
	var per_pagina_sel = document.getElementById("per_page");
	var per_pagina = per_pagina_sel.options[per_pagina_sel.selectedIndex].value;

    if (keyword == undefined || keyword == '') keyword = -1;
    if (val1 == undefined || val1 == '') val1 = -1;
    if (val2 == undefined || val2 == '') val2 = -1;
    set_comenzi_row(); // pentru scoaterea sumelor executante si solicitante
	sndReqNew('AJAX_proxy.php', 'f=render_comenzi&per_pag='+per_pagina+'&pagina='+pagina+'&comanda_incasata='+comanda_incasata+'&comanda_platita='+comanda_platita+'&scadenta_incasare='+scadenta_incasare+'&scadenta_plata='+scadenta_plata+'&f_sol='+f_sol+'&f_exec='+f_exec+'&camp='+camp+'&keyword='+keyword+'&val1='+val1+'&val2='+val2+'&sau_si='+sau_si, id_rezultat, '', 1);
}

function sterge_firma(id_firma, place_from) {
	// verific daca sunt comenzi cu id_firma_sol sau id_firma_exec egal cu id_firma...
	// daca DA voi atentiona sa stearga comenzile si apoi sa stearga firma
	// daca NU voi sterge firma si voi goli cache-ul
	if (place_from == 'from_view_firma') {
 	
		sndReqNew('AJAX_proxy.php', 'f=sterge_firma&id_firma='+id_firma, '', 'after_sterge_firma_from_view(response);', 0);
	}
	else {
		var pagina = document.getElementById('pagina').value;
		var per_pag = document.getElementById('per_pag').value;	
		var keyword = document.getElementById('keyword').value;
		var camp = document.getElementById('camp').value;
		var order = document.getElementById('order').value;	
		var camp_order = document.getElementById('camp_order').value;
		var tip_firma = document.getElementById('tip_firma_f').value;
		
		sndReqNew('AJAX_proxy.php', 'f=sterge_firma&id_firma='+id_firma, '', "after_sterge_firma(response,pagina,per_pag,'"+keyword+"','"+order+"','"+camp+"','"+camp_order+"','"+tip_firma+"')", 0);
	}
}

function after_sterge_firma_from_view(response) {
    if (response == -1000) {
        //adica firma nu poate fi stearsa pentru ca sunt comenzi in care apare;
        alert(LANG_Firma_nu_poate_fi_stearsa);
    }
    else {        
        clearCacheNow();
        document.location = 'show_firms.php';
    }
}

function after_sterge_firma(response, pagina, per_pag, keyword, order, camp, camp_order, tip_firma) {
	
    if (response == -1000) {
        //adica firma nu poate fi stearsa pentru ca sunt comenzi in care apare;
        alert(LANG_Firma_nu_poate_fi_stearsa);
    }
    else {        
        clearCacheNow();
        if (order == 'ASC') order = 'DESC'; else order = 'ASC';
        sndReqNew('AJAX_proxy.php', 'f=render_firme&order='+order+'&keyword='+keyword+'&camp='+camp+'&camp_order='+camp_order+'&tip_firma='+tip_firma+'&id_client='+id_client+'&per_pag='+per_pag+'&pagina='+pagina, 'content_firme', '', 1)
    }
}

function redirect_view_comenzi() {	
	alert(Lang_comanda_stearsa_cu_succes);
	window.location.href = 'show_comenzi.php';	
}

function sterge_comanda2(id) {
	clearCacheNow(); 	
	sndReqNew('AJAX_proxy.php', 'f=sterge_comanda_din_view&id_comanda='+id, '', 'redirect_view_comenzi()', 1);			
}

function sterge_comanda(id_comanda) {
	
	// verific daca sunt plati sau incasari in comanda respectiva
	// daca DA voi atentiona ca nu poate fi stearsa pentru ca bla bla bla....
	// daca NU voi sterge comanda si voi goli cache-ul
	// aceasta informatie o preiau din hidden field-uri
	
	if (document.getElementById('notice_msg')) document.getElementById('notice_msg').innerHTML = "";
	var camp_nume = 'stare_incasare_sol' + id_comanda;
	
	var stare_incasare_sol = document.getElementById(camp_nume).value;
	
	camp_nume = 'stare_plata_exec' + id_comanda;
	var stare_plata_exec = document.getElementById(camp_nume).value;
	    
    var per_pag = document.getElementById('per_pag').value;    
    var pagina = document.getElementById('pagina').value;    
    var comanda_incasata = document.getElementById('comanda_incasata').value;
    var comanda_platita = document.getElementById('comanda_platita').value;        
    var scadenta_incasare = document.getElementById('scadenta_incasare').value;        
    var scadenta_plata = document.getElementById('scadenta_plata').value;        
    var f_sol = document.getElementById('f_sol').value;        
    var f_exec = document.getElementById('f_exec').value;                
    var keyword = document.getElementById('keyword').value;
    var camp = document.getElementById('camp').value;
	var camp_sort = document.getElementById('camp_sort').value;                
    var order = document.getElementById('order_sort').value;            
    
	if (document.getElementById('val1')) var val1 = document.getElementById('val1').value;
	else val1 = -1;
	if (document.getElementById('val2')) var val2 = document.getElementById('val2').value;	            
	else val2 = -1;
	
    var pret_min = document.getElementById('pret_min').value;
    var f_sol = document.getElementById('f_sol').value;
    var f_exec = document.getElementById('f_exec').value;        
    var pret_max = document.getElementById('pret_max').value;        
    var cost_min = document.getElementById('cost_min').value;        
    var cost_max = document.getElementById('cost_max').value;        
    var data_scadenta_sol1 = document.getElementById('data_scadenta_sol1').value;        
    var data_scadenta_sol2 = document.getElementById('data_scadenta_sol2').value;        
    var data_scadenta_exec1 = document.getElementById('data_scadenta_exec1').value;        
    var data_scadenta_exec2 = document.getElementById('data_scadenta_exec2').value;        
    var data_factura_sol1 = document.getElementById('data_factura_sol1').value;        
    var data_factura_sol2 = document.getElementById('data_factura_sol2').value;        
    var data_factura_exec1 = document.getElementById('data_factura_exec1').value;        
    var data_factura_exec2 = document.getElementById('data_factura_exec2').value;        
//    var incasata = document.getElementById('incasata').value;        
//    var platita = document.getElementById('platita').value;        
    var sc_incasare = document.getElementById('sc_incasare').value;        
    var sc_plata = document.getElementById('sc_plata').value;        
    var cond_firme = document.getElementById('cond_firme').value;                                        
    
	if (stare_incasare_sol > 0 || stare_plata_exec > 0) {
		//adica comanda nu poate fi stearsa pentru ca sunt comenzi in care apare;
		var raspuns = confirm(LANG_Comanda_contine_plati);
		if (raspuns) {
			//atunci voi sterge comanda impreauna cu incasarile/platile
			//prima data golesc cache-ul
			
			clearCacheNow(); 
			//apoi voi sterge!
			sndReqNew('AJAX_proxy.php', 'f=sterge_comanda&id_comanda='+id_comanda+'&per_pag='+per_pag+'&pagina='+pagina+'&comanda_incasata='+comanda_incasata+'&comanda_platita='+comanda_platita+'&scadenta_incasare='+scadenta_incasare+'&scadenta_plata='+scadenta_plata+'&f_sol='+f_sol+'&f_exec='+f_exec+'&camp='+camp+'&order='+order+'&keyword='+keyword+'&val1='+val1+'&val2='+val2+'&pret_min='+pret_min+'&f_sol='+f_sol+'&f_exec='+f_exec+'&pret_max='+pret_max+'&cost_min='+cost_min+'&cost_max='+cost_max+'&data_scadenta_sol1='+data_scadenta_sol1+'&data_scadenta_sol2='+data_scadenta_sol2+'&data_scadenta_exec1='+data_scadenta_exec1+'&data_scadenta_exec2='+data_scadenta_exec2+'&data_factura_sol1='+data_factura_sol1+'&data_factura_sol2='+data_factura_sol2+'&data_factura_exec1='+data_factura_exec1+'&data_factura_exec2='+data_factura_exec2+'&sc_incasare='+sc_incasare+'&sc_plata='+sc_plata+'&cond_firme='+cond_firme+'&camp_sort='+camp_sort, 'pag_and_content', '', 1);			
		}
	}
	else {		
		clearCacheNow(); 
		sndReqNew('AJAX_proxy.php', 'f=sterge_comanda&id_comanda='+id_comanda+'&&per_pag='+per_pag+'&pagina='+pagina+'&comanda_incasata='+comanda_incasata+'&comanda_platita='+comanda_platita+'&scadenta_incasare='+scadenta_incasare+'&scadenta_plata='+scadenta_plata+'&f_sol='+f_sol+'&f_exec='+f_exec+'&camp='+camp+'&order='+order+'&keyword='+keyword+'&val1='+val1+'&val2='+val2+'&pret_min='+pret_min+'&f_sol='+f_sol+'&f_exec='+f_exec+'&pret_max='+pret_max+'&cost_min='+cost_min+'&cost_max='+cost_max+'&data_scadenta_sol1='+data_scadenta_sol1+'&data_scadenta_sol2='+data_scadenta_sol2+'&data_scadenta_exec1='+data_scadenta_exec1+'&data_scadenta_exec2='+data_scadenta_exec2+'&data_factura_sol1='+data_factura_sol1+'&data_factura_sol2='+data_factura_sol2+'&data_factura_exec1='+data_factura_exec1+'&data_factura_exec2='+data_factura_exec2+'&sc_incasare='+sc_incasare+'&sc_plata='+sc_plata+'&cond_firme='+cond_firme+'&camp_sort='+camp_sort, 'pag_and_content', '', 1);            
	}	
}

function introdu_cache_prima_data_firme(per_pag, id_client, camp, order, id_rezultat) {
	//aceasta functie o chem atunci cand randez prima data firmele pentru a baga in cache primul request;!!
	
    //preiau informatiile din formul de filtrare
    var tip_firma_sel = document.getElementById("tip_firma");
    var tip_firma = tip_firma_sel.options[tip_firma_sel.selectedIndex].value;
    
    //preiau informatiile din formul de cautare
    var keyword = document.getElementById("keyword").value;
        
    var camp_sel = document.getElementById("camp_search");
    var camp = camp_sel.options[camp_sel.selectedIndex].value;
    
    //preiau cate pe pagina
    var per_page_sel = document.getElementById("per_page");
    var per_pagina = per_page_sel.options[per_page_sel.selectedIndex].value;
    var conditie = 'id_client = ' + id_client;                                                                        
    
    addToCache('AJAX_proxy.php', 'f=render_firme&id_client='+id_client+'&pagina=0&per_pag='+per_pag+'&conditie='+conditie+'&camp='+camp+'&order='+order, id_rezultat);
}

function introdu_cache_prima_data_comenzi(per_pag, id_client, camp, order, id_rezultat) {
	//aceasta functie o chem atunci cand randez prima data comenzile pentru a baga in cache primul request;!!
	
	//preiau informatiile din formul de filtrare

	var comanda_incasata_sel = document.getElementById("incasata_sel");
	var comanda_incasata = comanda_incasata_sel.options[comanda_incasata_sel.selectedIndex].value;	
	
	var comanda_platita_sel = document.getElementById("platita_sel");
	var comanda_platita = comanda_platita_sel.options[comanda_platita_sel.selectedIndex].value;	
	
	var scadenta_incasare_sel = document.getElementById("sc_incasare_sel");
	var scadenta_incasare = scadenta_incasare_sel.options[scadenta_incasare_sel.selectedIndex].value;	
	
	var scadenta_plata_sel = document.getElementById("sc_plata_sel");
	var scadenta_plata = scadenta_plata_sel.options[scadenta_plata_sel.selectedIndex].value;	
	
	var f_sol_sel = document.getElementById("f_sol_sel");
	var f_sol = f_sol_sel.options[f_sol_sel.selectedIndex].value;	
	
	var sau_si_sel = document.getElementById("sau_si");
	var sau_si = sau_si_sel.options[sau_si_sel.selectedIndex].value;
	
	var f_exec_sel = document.getElementById("f_exec_sel");
	var f_exec = f_exec_sel.options[f_exec_sel.selectedIndex].value;	
	
	//preiau informatiile din formul de cautare

	var keyword = document.getElementById("keyword").value;
		
	var camp_sel = document.getElementById("camp_sel");
	var campul = camp_sel.options[camp_sel.selectedIndex].value;

	//preiau cate pe pagina
	var per_pagina_sel = document.getElementById("per_page");
	var per_pagina = per_pagina_sel.options[per_pagina_sel.selectedIndex].value;
		
	//acum ca am toate informatiile trebuie sa creez conditia
	
	var conditie = 'comanda.id_client = ' + id_client + ' AND comanda.deleted = 0'; //conditia default
	if (comanda_incasata != -1)
		conditie = conditie + ' AND stare_incasare_sol = ' + comanda_incasata;

	if (comanda_platita != -1)
		conditie = conditie + ' AND stare_plata_exec = ' +  comanda_platita
		
	if (scadenta_incasare != -1)
		conditie = conditie + '  AND DATEDIFF(CURDATE(), data_scadenta_sol) <= ' +  (scadenta_incasare * 7);

	if (scadenta_plata != -1)
		conditie = conditie + ' AND DATEDIFF(CURDATE(), data_scadenta_exec) <= ' +  (scadenta_plata * 7);
	
	if (f_sol != -1)
		conditie = conditie + ' AND id_firma_sol = ' +  f_sol;
	
	if (f_exec != -1)
		conditie = conditie + ' AND id_firma_exec = ' +  f_exec;
	
	if (keyword != '') conditie = conditie + ' AND ' + campul + " LIKE '%" +  keyword + "%'";

	conditie = conditie + '&camp=comanda.id_firma_sol&order=ASC'; 
	addToCache('AJAX_proxy.php', 'f=render_comenzi&id_client='+id_client+'&pagina=0&per_pag='+per_pag+'&conditie='+conditie, id_rezultat);
}

function arata_modal_cautare_avansata_comenzi(id_client) {
	var per_pag = document.getElementById('per_page').value;
	sndReqNew('cautare_avansata_comenzi.php','id_client='+id_client+'&per_pag='+per_pag, '', 'displayMessage(response)', 0);
}

function date_for_server(date) {
    var ch = date.charAt(2);
    var d_arr = date.split(ch);
    var new_date = d_arr[2] + "-" + d_arr[1] + "-" + d_arr[0];
    return new_date; 
}

function new_cauta_confirm() {
	
	//preiau informatiile din formul de cautare avansata

	var data_scadenta_sol1 = document.getElementById("data_scadenta_sol").value;
    if (data_scadenta_sol1.length > 0) data_scadenta_sol1 = date_for_server(data_scadenta_sol1);

	var data_scadenta_sol2 = document.getElementById("data_scadenta_sol22").value;
    if (data_scadenta_sol2.length > 0) data_scadenta_sol2 = date_for_server(data_scadenta_sol2);

	var data_scadenta_exec1 = document.getElementById("data_scadenta_exec").value;
    if (data_scadenta_exec1.length > 0) data_scadenta_exec1 = date_for_server(data_scadenta_exec1);
    
	var data_scadenta_exec2 = document.getElementById("data_scadenta_exec22").value;
    if (data_scadenta_exec2.length > 0) data_scadenta_exec2 = date_for_server(data_scadenta_exec2);
    	
	var data_factura_sol1 = document.getElementById("data_factura_sol").value;
    if (data_factura_sol1.length > 0) data_factura_sol1 = date_for_server(data_factura_sol1);
        
	var data_factura_sol2 = document.getElementById("data_factura_sol22").value;
    if (data_factura_sol2.length > 0) data_factura_sol2 = date_for_server(data_factura_sol2);    

	var data_factura_exec1 = document.getElementById("data_factura_exec").value;
    if (data_factura_exec1.length > 0) data_factura_exec1 = date_for_server(data_factura_exec1);    
        
	var data_factura_exec2 = document.getElementById("data_factura_exec22").value;
    if (data_factura_exec2.length > 0) data_factura_exec2 = date_for_server(data_factura_exec2);        
	
	var incasata_sel = document.getElementById("incasata2");
	var comanda_incasata = incasata_sel.options[incasata_sel.selectedIndex].value;	
	
	var platita_sel = document.getElementById("platita2");
	var comanda_platita = platita_sel.options[platita_sel.selectedIndex].value;		
	
	var sc_incasare_sel = document.getElementById("sc_incasare2");
	var sc_incasare = sc_incasare_sel.options[sc_incasare_sel.selectedIndex].value;	

	var sc_plata_sel = document.getElementById("sc_plata2");
	var sc_plata = sc_plata_sel.options[sc_plata_sel.selectedIndex].value;	
	
	var f_sol_sel = document.getElementById("f_sol2");
	var f_sol = f_sol_sel.options[f_sol_sel.selectedIndex].value;		
	
	var cond_firme_sel = document.getElementById("sau_si2");
	var cond_firme = cond_firme_sel.options[cond_firme_sel.selectedIndex].value;		
	
	var f_exec_sel = document.getElementById("f_exec2");
	var f_exec = f_exec_sel.options[f_exec_sel.selectedIndex].value;	
	
	
	//preiau informatiile din formul de cautare
	var spancontainer = document.getElementById('campuri2');
	
	if (spancontainer.innerHTML.length < 500) {
		var keyword = document.getElementById("keyword2").value;
	}
	else {				
		var val1 = document.getElementById("val1").value;
		var val2 = document.getElementById("val2").value;		
	}	
		
	var camp_sel = document.getElementById("camp2");
	var camp = camp_sel.options[camp_sel.selectedIndex].value;
	
    if (keyword == undefined || keyword == '') keyword = -1;
    if (val1 == undefined || val1 == '') val1 = -1;
    if (val2 == undefined || val2 == '') val2 = -1;
		
	//preiau pretul si costul
	var pret_min = document.getElementById("pret1").value;
	var pret_max = document.getElementById("pret2").value;
	
	var cost_min = document.getElementById("cost1").value;
	var cost_max = document.getElementById("cost2").value;
	
	//acum ca am toate informatiile trebuie sa creez conditia
	var sau_si_sel = document.getElementById("sau_si2");
	var sau_si = sau_si_sel.options[sau_si_sel.selectedIndex].value;
    
	closeMessage();
	comenzi_indici = [];
	clearCacheNow();
	set_comenzi_row();
	sndReqNew('AJAX_proxy.php', 'f=render_comenzi&pagina=0&camp='+camp+'&keyword='+keyword+'&pret_min='+pret_min+'&f_sol='+f_sol+'&f_exec='+f_exec+'&pret_max='+pret_max+'&cost_min='+cost_min+'&cost_max='+cost_max+'&data_scadenta_sol1='+data_scadenta_sol1+'&data_scadenta_sol2='+data_scadenta_sol2+'&data_scadenta_exec1='+data_scadenta_exec1+'&data_scadenta_exec2='+data_scadenta_exec2+'&data_factura_sol1='+data_factura_sol1+'&data_factura_sol2='+data_factura_sol2+'&data_factura_exec1='+data_factura_exec1+'&data_factura_exec2='+data_factura_exec2+'&comanda_incasata='+comanda_incasata+'&comanda_platita='+comanda_platita+'&sc_incasare='+sc_incasare+'&sc_plata='+sc_plata+'&cond_firme='+cond_firme+'&sau_si='+sau_si+'&val1='+val1+'&val2='+val2, 'pag_and_content', '', 1)
}

function arata_modal_user() {
	sndReqNew('modal_add_user.php','', '','displayMessage(response); document.getElementById(\'username\').focus();', 0);    
}

function select_all_permissions(selected) {
    document.getElementById("perm_comenzi").checked = selected;
    document.getElementById("perm_comenzi_dupa_confirmare").checked = selected;
    document.getElementById("perm_firme").checked = selected;
    document.getElementById("perm_edit_clienti").checked = selected;
    document.getElementById("perm_edit_users").checked = selected;
    document.getElementById("perm_plati").checked = selected;
    document.getElementById("perm_statistici").checked = selected;
    document.getElementById("perm_admin_abonament").checked = selected;
}

function new_user_confirm(optiune, index) {
	
	var username = document.getElementById("username").value;
	var nume = document.getElementById("nume").value;
	var prenume = document.getElementById("prenume").value;
	var email = document.getElementById("email").value;
	
    var perm_comenzi = document.getElementById("perm_comenzi").checked;
    var perm_comenzi_dupa_confirmare = document.getElementById("perm_comenzi_dupa_confirmare").checked;
    var perm_firme = document.getElementById("perm_firme").checked;
    var perm_edit_clienti = document.getElementById("perm_edit_clienti").checked;
    var perm_edit_users = document.getElementById("perm_edit_users").checked;
    var perm_plati = document.getElementById("perm_plati").checked;
    var perm_statistici = document.getElementById("perm_statistici").checked;
	var perm_admin_abonament = document.getElementById("perm_admin_abonament").checked;
	
	// Fa campurile albe din nou
    document.getElementById('td_username').className = '';
    document.getElementById('td_nume').className = '';
    document.getElementById('td_prenume').className = '';
    document.getElementById('td_email').className = '';

    var submit = "f=ajax_create_new_user&optiune="+optiune+"&index="+index+"&username="+username+"&nume="+nume+"&prenume="
    +prenume+"&email="+email;
    
    if (perm_comenzi)
        submit += "&perm_comenzi=1";
    if (perm_comenzi_dupa_confirmare)
        submit += "&perm_comenzi_dupa_confirmare=1";
    if (perm_firme)
        submit += "&perm_firme=1";
    if (perm_edit_clienti)
        submit += "&perm_edit_clienti=1";
    if (perm_edit_users)
        submit += "&perm_edit_users=1";
    if (perm_plati)
        submit += "&perm_plati=1";
    if (perm_statistici)
        submit += "&perm_statistici=1";
    if (perm_admin_abonament)
        submit += "&perm_admin_abonament=1";
        
	//submit the data to the server
	sndReqNew('AJAX_proxy.php', submit, '', 'closeMessage(); sndReqNew(\'AJAX_proxy.php\', \'f=render_users_table\', \'users\', \'\', 0)', 0);
    
}

function print_factura_button() {
	remove_by_ID('notice_msg');
	sndReqNew('modal_print_factura.php','index='+comenzi_indici[0], '','displayMessage(response); document.getElementById(\'curs\').focus();', 0);
}

function show_factura_din_comanda(id_comanda) {
    sndReqNew('modal_print_factura.php','index='+id_comanda, '','displayMessage(response); document.getElementById(\'curs\').focus();', 0);
}

function edit_user(index) {
	sndReqNew('modal_add_user.php','index='+index,'', 'displayMessage(response);', 0);
}

function sterge_user(index) {
	if (confirm(LANG_Vreti_sa_stergeti_userul)) {
		sndReqNew('AJAX_proxy.php', 'f=sterge_user&index='+index, 'users', '', 0);		
	}
}

function set_firme_row_and_click(id_firma) {
	//fac checbox-ul bifat...respectiv debifez dupa caz
	nume = "ch" + id_firma;	
	ch = document.getElementById(nume);
	
	if (click_checkbox == 0) {
		if (ch.checked == true) ch.checked = false;
		else ch.checked = true;
	}
	
	click_checkbox = 0;
	//introduc intr-un vector id-urile firmelor selectate pentru optiunile de delete respectiv edit!
	exista = false;
	for (i = 0; i < firme_indici.length; i++) {
		if (firme_indici[i] == ch.value) {			
			exista = true;			
			break;
		}
	}
	
	if (exista == false) {
		firme_indici.push(ch.value);		
	}
	else {
		firme_indici.splice(i, 1);
	}
	set_firme_row();
}

function set_firme_row() {
	if (firme_indici.length > 1) {
		//fac disable la button
		if (document.getElementById('edit_firma_buton')) document.getElementById('edit_firma_buton').disabled = true;
		if (document.getElementById('sterge_firma_buton')) document.getElementById('sterge_firma_buton').disabled = true;
		if (document.getElementById('view_firma_buton')) document.getElementById('view_firma_buton').disabled = true;
		if (document.getElementById('print_firma_buton')) document.getElementById('print_firma_buton').disabled = true;
	}
	else {
		if (document.getElementById('edit_firma_buton')) document.getElementById('edit_firma_buton').disabled = true;
		if (document.getElementById('sterge_firma_buton')) document.getElementById('sterge_firma_buton').disabled = true;
		if (document.getElementById('view_firma_buton')) document.getElementById('view_firma_buton').disabled = true;
		if (document.getElementById('print_firma_buton')) document.getElementById('print_firma_buton').disabled = true;
	}
	if (firme_indici.length == 1) {		
		if (document.getElementById('sterge_firma_buton')) document.getElementById('sterge_firma_buton').disabled = false;
		if (document.getElementById('edit_firma_buton')) document.getElementById('edit_firma_buton').disabled = false;
		if (document.getElementById('view_firma_buton')) document.getElementById('view_firma_buton').disabled = false;
		if (document.getElementById('print_firma_buton')) document.getElementById('print_firma_buton').disabled = false;
	}
}

function set_comenzi_row_and_click(id_comanda) {
	
	//fac checbox-ul bifat...respectiv debifez dupa caz
	var nume = "ch" + id_comanda;	
	var ch = document.getElementById(nume);

	if (click_checkbox == 0) {
		if (ch.checked == true) 
			ch.checked = false;
		else 
			ch.checked = true;
	}
	
	click_checkbox = 0;
				
	//introduc intr-un vector id-urile comenzilor selectate pentru optiunile de delete respectiv edit!
	var exista = false;
	for (i = 0; i < comenzi_indici.length; i++) {
		if (comenzi_indici[i] == ch.value) {			
			exista = true;			
			break;
		}
	}
	
	if (exista == false) 
		comenzi_indici.push(ch.value);		
	else 
		comenzi_indici.splice(i, 1);
			
	set_comenzi_row(id_comanda);
}

function set_comenzi_row() {

	if (comenzi_indici.length > 1) {
		//fac disable la button	
		if (document.getElementById('edit_comanda_buton')) document.getElementById('edit_comanda_buton').disabled = true;
		if (document.getElementById('sterge_comanda_buton')) document.getElementById('sterge_comanda_buton').disabled = true;
		if (document.getElementById('view_comanda_buton')) document.getElementById('view_comanda_buton').disabled = true;
		if (document.getElementById('print_comanda_buton')) document.getElementById('print_comanda_buton').disabled = true;
		if (document.getElementById('plata_comanda_buton')) document.getElementById('plata_comanda_buton').disabled = false;
		if (document.getElementById('plata_comanda_buton')) document.getElementById('plata_comanda_buton').disabled = false;
        if (document.getElementById('view_plata_button')) document.getElementById('view_plata_button').disabled = true;
        if (document.getElementById('view_incasari_button')) document.getElementById('view_incasari_button').disabled = true;
        if (document.getElementById('plata_incasare_comanda_buton')) document.getElementById('plata_incasare_comanda_buton').disabled = true;
        if (document.getElementById('duplicare_comanda_button')) document.getElementById('duplicare_comanda_button').disabled = true;
        if (document.getElementById('print_factura')) document.getElementById('print_factura').disabled = true;
	}
	else {
		if (document.getElementById('edit_comanda_buton')) document.getElementById('edit_comanda_buton').disabled = true;
		if (document.getElementById('sterge_comanda_buton')) document.getElementById('sterge_comanda_buton').disabled = true;
		if (document.getElementById('view_comanda_buton')) document.getElementById('view_comanda_buton').disabled = true;
		if (document.getElementById('print_comanda_buton')) document.getElementById('print_comanda_buton').disabled = true;
		if (document.getElementById('plata_comanda_buton')) document.getElementById('plata_comanda_buton').disabled = true;
		if (document.getElementById('incasare_comanda_buton')) document.getElementById('incasare_comanda_buton').disabled = true;
        if (document.getElementById('view_plata_button')) document.getElementById('view_plata_button').disabled = true;
        if (document.getElementById('view_incasari_button')) document.getElementById('view_incasari_button').disabled = true;
        if (document.getElementById('duplicare_comanda_button')) document.getElementById('duplicare_comanda_button').disabled = true;
        if (document.getElementById('plata_incasare_comanda_buton')) document.getElementById('plata_incasare_comanda_buton').disabled = true;
        if (document.getElementById('print_factura')) document.getElementById('print_factura').disabled = true;
	}
	if (comenzi_indici.length == 1) {		
		if (document.getElementById('sterge_comanda_buton')) document.getElementById('sterge_comanda_buton').disabled = false;
		if (document.getElementById('edit_comanda_buton')) document.getElementById('edit_comanda_buton').disabled = false;
		if (document.getElementById('view_comanda_buton')) document.getElementById('view_comanda_buton').disabled = false;
		if (document.getElementById('print_comanda_buton')) document.getElementById('print_comanda_buton').disabled = false;
		if (document.getElementById('plata_comanda_buton')) document.getElementById('plata_comanda_buton').disabled = false;
		if (document.getElementById('incasare_comanda_buton')) document.getElementById('incasare_comanda_buton').disabled = false;
        if (document.getElementById('view_plata_button')) document.getElementById('view_plata_button').disabled = false;
        if (document.getElementById('view_incasari_button')) document.getElementById('view_incasari_button').disabled = false;
        
        set_incasare_plata_buton_visible_invisible();
        
        if (document.getElementById('duplicare_comanda_button')) document.getElementById('duplicare_comanda_button').disabled = false;
        if (document.getElementById('print_factura')) document.getElementById('print_factura').disabled = false;
	}
	
	//va trebui sa calculez sumele!!
	//pe rand pentru fiecare moneda!!

	for (i = 0; i < 100; i++) {
		sume_sol[i] = 0;
		sume_exec[i] = 0;
	}
	
	for (i = 0; i < comenzi_indici.length; i++) {

		var nume = 'moneda_sol' + comenzi_indici[i];		
		var moneda_sol = document.getElementById(nume).value;
				
		var nume = 'suma_totala_sol' + comenzi_indici[i];
		var s_sol = document.getElementById(nume).value;		
		sume_sol[moneda_sol] = parseInt(parseInt(sume_sol[moneda_sol]) + parseInt(s_sol));
		
		var nume = 'moneda_exec' + comenzi_indici[i];
		var moneda_exec = document.getElementById(nume).value;
		
		var nume = 'suma_totala_exec' + comenzi_indici[i];
		var s_exec = document.getElementById(nume).value;		
		sume_exec[moneda_exec] = parseInt(parseInt(sume_exec[moneda_exec]) + parseInt(s_exec));		
	}
	
	var status_plata = document.getElementById('status_plata');
	if (comenzi_indici.length > 0) {
		var text = '';
		text = '<div align="left" style="width: 100%">' + LANG_Total_suma_solicitant + ': ';
		
		for (i = 0; i < sume_sol.length; i++) {
			if (sume_sol[i] != 0 && parseInt(sume_sol[i]) > 0) {
				//moneda va fi i				
				text += '<b>' + monede[i] + '</b> ' + sume_sol[i] + '; ';
			}
		}
		
		text += '<br />' + LANG_Total_suma_executant + ': ';
		for (i = 0; i < sume_exec.length; i++) {			
			if (sume_exec[i] != 0 && parseInt(sume_exec[i]) > 0) {
				//moneda va fi i
				text += '<b>' + monede[i] + '</b> ' + sume_exec[i] + '; ';
			}
		}
		text += '</div>';
		status_plata.innerHTML = text;
	}
	else {
		
		status_plata.innerHTML = LANG_Total_suma_solicitant + "<br />" + LANG_Total_suma_executant;
	}
	
}

function sterge_comanda_buton() {	
	if (confirm(LANG_Vreti_sa_stergeti_comanda)) {		
		var id;
		if (comenzi_indici[0] == undefined) {
			id = document.getElementById('id_comanda').value;
		}	
		else {
			id	= comenzi_indici[0];
			comenzi_indici.length = 0;
			comenzi_indici = [];  			
		}			
		sterge_comanda(id);	
	}
}

function sterge_comanda_buton_view() {
	if (confirm(LANG_Vreti_sa_stergeti_comanda)) {		
		id = document.getElementById('id_comanda').value;
		sterge_comanda2(id);	
	}
}

function edit_firma_buton() {	
	if (firme_indici.length == 0) {
		var id = document.getElementById('id_firma').value;
		window.location.href = 'add_firma.php?id=' + id;
	}
	else window.location.href = 'add_firma.php?id=' + firme_indici[0];
}

function add_firma_buton() {	
	window.location.href = 'add_firma.php';
}

function add_comanda_buton() {	
	window.location.href = 'add_comanda.php';
}

function edit_comanda_buton() {
	var id;
	if (comenzi_indici[0] == undefined) {
		id = document.getElementById('id_comanda').value;
	}	
	else id	= comenzi_indici[0];	
	window.location.href = 'add_comanda.php?id=' + id;
}

function view_comanda_buton() {	
	window.location.href = 'view_comanda.php?id=' + comenzi_indici[0];
}

function cauta_contact_buton() {	
	window.location.href = 'cauta_contacte.php';
}

function back_to_home() {	
	window.location.href = 'home.php';
}

function fa_plata_incasare(tip, id_comanda) {	
	window.location.href = 'add_plata.php?tip=' + tip + '&id_comanda=' + id_comanda;
}

function multe_firme(index) {
	sndReqNew('AJAX_proxy.php', 'f=arata_firme_hp&cond_partiala=ultime_adaugate', '', 'window.location.href = \'show_firms.php\'', 1)
}

function multe_comenzi(camp, valoare) {	
	sndReqNew('AJAX_proxy.php', 'f=introdu_sesiune&camp='+camp+'&valoare='+valoare, '', 'window.location.href = \'show_comenzi.php\'', 1)
}

function view_firma_buton() {	
	window.location.href = 'view_firma.php?id=' + firme_indici[0];
}

function view_firms_buton() {	
	window.location.href = 'show_firms.php';
}

function show_comenzi_buton() {
	window.location.href = 'show_comenzi.php';
}

function duplicare_comanda_button() {
    document.location = 'add_comanda.php?idd=' + comenzi_indici[0];
}

function sterge_firma_buton() {		
	if (confirm(LANG_Vreti_sa_stergeti_firma)) {
		if (firme_indici[0] == undefined)
			var id_firma = document.getElementById('id_firma').value;
		else 
			var id_firma = firme_indici[0];
		sterge_firma(id_firma, 'from_view_firma');	
	}
}

function print_firma_buton() {
	var sir = '';
	for (i = 0; i < firme_indici.length; i++) {
		sir = sir + firme_indici[i] + ';';		
	}
	
	if (firme_indici.length == 0) {		
		var id = document.getElementById('id_firma').value;
		document.location = "printFirme.php?output=0&indecsi="+id+';';
	}
	else document.location = "printFirme.php?output=0&indecsi="+sir; 
}

function print_comanda_buton() {
	var sir = '';
	for (i = 0; i < comenzi_indici.length; i++) {
		sir = sir + comenzi_indici[i] + ';';		
	}

	if (comenzi_indici.length == 0) {		
		var id = document.getElementById('id_comanda').value;	
		document.location = "printComenzi.php?output=0&indecsi="+id;
	}	
	else document.location = "printComenzi.php?output=0&indecsi="+sir; 
}

function remove_by_ID(elem_id) {
	if (document.getElementById(elem_id)) {
		elem = document.getElementById(elem_id);
		elem.parentNode.removeChild(elem);	
	}	
} 

function plata_comanda_buton() {		
	remove_by_ID('notice_msg');
    
    IDElementForm = "stare_incasare_sol" + comenzi_indici[0];
    sumaElementForm = "suma_totala_sol" + comenzi_indici[0];
		
	if (comenzi_indici.length == 1 && document.getElementById(IDElementForm).value == "2") {				
		suma = document.getElementById(sumaElementForm).value;				
		alert(Lang_Comanda_Platita_Integral + " Total: " + suma);			
	}
	else {	
		toate = 1;
		for (i = 0; i < comenzi_indici.length; i++) { 
			IDElementForm = "stare_plata_exec" + comenzi_indici[i];
			if (document.getElementById(IDElementForm).value != "2")
				toate = 0;
		}
		if (toate == 1) {
			alert(Lang_Comanda_Platita_Integral);		
		}
		else {		
			var sir = '';
			for (i = 0; i < comenzi_indici.length; i++) {
				sir = sir + comenzi_indici[i]
				if (i == comenzi_indici.length - 1)
					sir = sir;		
				else
					sir = sir + '_';		
			}	
			
			if (comenzi_indici.length == 1)
				document.location = "add_plata.php?tip=1&id_comanda="+sir;
			else 
				document.location = "add_plati.php?tip=1&id_comanda="+sir;
		}
	}
}

function plata_comanda_from_vizualizare_button() {
    var url = document.location.toString();
    var index = url.indexOf('?');
    var idComanda = url.substring(index + 4, url.length);
    document.location = "add_plata.php?tip=1&id_comanda=" + idComanda;
}

function incasare_comanda_from_vizualizare_button() {
    var url = document.location.toString();
    var index = url.indexOf('?');
    var idComanda = url.substring(index + 4, url.length);
    document.location = "add_plata.php?tip=0&id_comanda=" + idComanda;
}

function incasare_comanda_buton() {	
	remove_by_ID('notice_msg');
	IDElementForm = "stare_incasare_sol" + comenzi_indici[0];
	sumaElementForm = "suma_totala_sol" + comenzi_indici[0];
		
	if (comenzi_indici.length == 1 && document.getElementById(IDElementForm).value == "2") {				
		suma = document.getElementById(sumaElementForm).value;				
		alert(Lang_Comanda_Incasata_Integral + " Total: " + suma);			
	}
	else {
		//verificam daca toate comenziile sunt incasate total
		toate = 1;
		for (i = 0; i < comenzi_indici.length; i++) { 
			IDElementForm = "stare_incasare_sol" + comenzi_indici[i];
			if (document.getElementById(IDElementForm).value != "2")
				toate = 0;
		}
		if (toate == 1) {
			alert(Lang_Comenzi_Incasate_Integral);		
		}
		else {			
			var sir = '';
			for (i = 0; i < comenzi_indici.length; i++) {
				sir = sir + comenzi_indici[i]
				if (i == comenzi_indici.length - 1)
					sir = sir;		
				else
					sir = sir + '_';		
			}		
			if (comenzi_indici.length == 1)
				document.location = "add_plata.php?tip=0&id_comanda="+sir;
			else	
				document.location = "add_plati.php?tip=0&id_comanda="+sir;
		}
	}
}

function plata_incasare_comanda_buton() {
    var sir = '';
    sir = sir + comenzi_indici[0];
    document.location = "add_plata.php?tip=0&action=pac&id_comanda=" + sir;
}

function sorteaza_firme(coloana_sort, per_pag, id_client, camp, order, pagina_curenta, coloane_firme, keyword, tip_firma) {
	firme_indici.length = 0;
	firme_indici = [];
	clearCacheNow();
	remove_by_ID('notice_msg');	
	sndReqNew('AJAX_proxy.php', 'f=render_firme&keyword='+keyword+'&camp_order='+coloana_sort+'&tip_firma='+tip_firma+'&id_client='+id_client+'&per_pag='+per_pag+'&pagina='+pagina_curenta+'&camp='+camp+'&order='+order, 'content_firme', '', 1);
}

function sorteaza_comenzi(camp_sort, order) {
	remove_by_ID('notice_msg');
	comenzi_indici.length = 0;
	comenzi_indici = [];
	clearCacheNow();
	
	var per_pag = document.getElementById('per_pag').value;	
	var pagina = document.getElementById('pagina').value;	
	var comanda_incasata = document.getElementById('comanda_incasata').value;
	var comanda_platita = document.getElementById('comanda_platita').value;		
	var scadenta_incasare = document.getElementById('scadenta_incasare').value;		
	var scadenta_plata = document.getElementById('scadenta_plata').value;		
	var f_sol = document.getElementById('f_sol').value;		
	var f_exec = document.getElementById('f_exec').value;				
	var keyword = document.getElementById('keyword').value;
	var camp = document.getElementById('camp').value;
				
	var val1 = document.getElementById('val1_1').value;		
	var val2 = document.getElementById('val2_2').value;	
		
	var pret_min = document.getElementById('pret_min').value;
	var f_sol = document.getElementById('f_sol').value;
	var f_exec = document.getElementById('f_exec').value;		
	var pret_max = document.getElementById('pret_max').value;		
	var cost_min = document.getElementById('cost_min').value;		
	var cost_max = document.getElementById('cost_max').value;		
	var data_scadenta_sol1 = document.getElementById('data_scadenta_sol1').value;		
	var data_scadenta_sol2 = document.getElementById('data_scadenta_sol2').value;		
	var data_scadenta_exec1 = document.getElementById('data_scadenta_exec1').value;		
	var data_scadenta_exec2 = document.getElementById('data_scadenta_exec2').value;		
	var data_factura_sol1 = document.getElementById('data_factura_sol1').value;		
	var data_factura_sol2 = document.getElementById('data_factura_sol2').value;		
	var data_factura_exec1 = document.getElementById('data_factura_exec1').value;		
	var data_factura_exec2 = document.getElementById('data_factura_exec2').value;		
		
	var sc_incasare = document.getElementById('sc_incasare').value;		
	var sc_plata = document.getElementById('sc_plata').value;		
	var cond_firme = document.getElementById('cond_firme').value;	
	var sau_si = document.getElementById('sau_si').value;			
	set_comenzi_row();
	sndReqNew('AJAX_proxy.php', 'f=render_comenzi&sau_si='+sau_si+'&per_pag='+per_pag+'&pagina='+pagina+'&comanda_incasata='+comanda_incasata+'&comanda_platita='+comanda_platita+'&scadenta_incasare='+scadenta_incasare+'&scadenta_plata='+scadenta_plata+'&f_sol='+f_sol+'&f_exec='+f_exec+'&camp='+camp+'&order='+order+'&keyword='+keyword+'&val1='+val1+'&val2='+val2+'&pret_min='+pret_min+'&f_sol='+f_sol+'&f_exec='+f_exec+'&pret_max='+pret_max+'&cost_min='+cost_min+'&cost_max='+cost_max+'&data_scadenta_sol1='+data_scadenta_sol1+'&data_scadenta_sol2='+data_scadenta_sol2+'&data_scadenta_exec1='+data_scadenta_exec1+'&data_scadenta_exec2='+data_scadenta_exec2+'&data_factura_sol1='+data_factura_sol1+'&data_factura_sol2='+data_factura_sol2+'&data_factura_exec1='+data_factura_exec1+'&data_factura_exec2='+data_factura_exec2+'&sc_incasare='+sc_incasare+'&sc_plata='+sc_plata+'&cond_firme='+cond_firme+'&camp_sort='+camp_sort, 'pag_and_content', '', 1);	
}

function set_buton_visible_invisible_show_comenzi() {
	document.getElementById('sterge_comanda_buton').disabled = true;
	document.getElementById('print_comanda_buton').disabled = true;
	document.getElementById('edit_comanda_buton').disabled = true;
	document.getElementById('view_comanda_buton').disabled = true;	
	if (document.getElementById('plata_comanda_buton'))
		document.getElementById('plata_comanda_buton').disabled = true;	
	if (document.getElementById('incasare_comanda_buton')) document.getElementById('incasare_comanda_buton').disabled = true;	
    if (document.getElementById('view_plata_button')) document.getElementById('view_plata_button').disabled = true;    
    if (document.getElementById('view_incasari_button')) document.getElementById('view_incasari_button').disabled = true;
    
    set_incasare_plata_buton_visible_invisible();
    
    document.getElementById('duplicare_comanda_button').disabled = true;    
    document.getElementById('print_factura').disabled = true;
}

function set_incasare_plata_buton_visible_invisible() {
    if (comenzi_indici.length == 1) {
        if (document.getElementById('plata_incasare_comanda_buton')) {
            var IDElementFormPlata = "stare_plata_exec" + comenzi_indici[0];
            var IDElementFormIncasare = "stare_incasare_sol" + comenzi_indici[0];
            
            if (document.getElementById(IDElementFormPlata).value == "2" || document.getElementById(IDElementFormIncasare).value == "2") {
                if (document.getElementById('plata_incasare_comanda_buton')) document.getElementById('plata_incasare_comanda_buton').disabled = true;
            }
            else {
                if (document.getElementById('plata_incasare_comanda_buton')) document.getElementById('plata_incasare_comanda_buton').disabled = false;
            }
        }
    }
    else
        if (document.getElementById('plata_incasare_comanda_buton')) document.getElementById('plata_incasare_comanda_buton').disabled = true;
}

function set_buton_visible_invisible_add_comanda() {
//	document.getElementById('sterge_comanda_buton').disabled = true;
//	document.getElementById('print_comanda_buton').disabled = true;
//	document.getElementById('edit_comanda_buton').disabled = true;
//	document.getElementById('view_comanda_buton').disabled = true;	
}

function bifeaza() {
	click_checkbox = 1;
}

function schimba_chart_custom(criteriu, tip) {
	data1 = document.getElementById('data1').value;
	data2 = document.getElementById('data2').value;
	perioada = data1 + 'and' + data2;
	window.location.href = 'stats.php?criteriu=' + criteriu + '&perioada=' + perioada + '&tip=' + tip;
}

function dezgheata() {
	document.getElementById('cal1').disabled = false;
	document.getElementById('cal2').disabled = false;		
	document.getElementById('image2').disabled = false;	
	document.getElementById('image1').disabled = false;	
	document.getElementById('buton_custom').disabled = false;
    document.getElementById('data1').disabled=false;
    document.getElementById('data2').disabled=false;		
}

function curata() {
    document.getElementById('data1').value='';
    document.getElementById('data2').value='';
    document.getElementById('data1').disabled=true;
    document.getElementById('data2').disabled=true;
}


function calc_total_sol() {
    if (document.form1.suma_sol.value == '')
        document.form1.suma_sol.value = '0.00';
    if (document.form1.taxe_supl_to_sol.value == '')
        document.form1.taxe_supl_to_sol.value = '0.00';
    if (document.form1.penaliz_from_sol.value == '')
        document.form1.penaliz_from_sol.value = '0.00';
    var suma_sol = prepareNumberForServer(document.form1.suma_sol.value);
    var taxe_supl_to_sol = prepareNumberForServer(document.form1.taxe_supl_to_sol.value);
    var penaliz_from_sol = prepareNumberForServer(document.form1.penaliz_from_sol.value);
    
	if (!isNaN(suma_sol) && suma_sol != "" && !isNaN(taxe_supl_to_sol) && taxe_supl_to_sol != "" && !isNaN(penaliz_from_sol) && penaliz_from_sol != "")
		document.form1.suma_totala_sol.value = prepareFloatForUser(parseFloat(suma_sol) 
												+ parseFloat(taxe_supl_to_sol) 
												- parseFloat(penaliz_from_sol));
}

function calc_pret_pe_km() {
    if (document.form1.suma_sol.value == '')
        document.form1.suma_sol.value = '0.00';
    if (document.form1.suma_exec.value == '')
        document.form1.suma_exec.value = '0.00';
    if (document.form1.nr_km.value == '')
        document.form1.nr_km.value = '0.00';
    
    var suma_sol = prepareNumberForServer(document.form1.suma_sol.value);
    var suma_exec = prepareNumberForServer(document.form1.suma_exec.value);
    var nr_km = prepareNumberForServer(document.form1.nr_km.value);
    
    var pret_pe_km = '';
    
    if (!isNaN(nr_km) && nr_km != "" && nr_km != 0) {
        if (!isNaN(suma_sol) && suma_sol != "") {
            pret_pe_km = suma_sol / nr_km;
            pret_pe_km = prepareFloatForUser(pret_pe_km.toFixed(2));
            document.getElementById('pret_pe_km_sol').innerHTML = pret_pe_km;
        }
        if (!isNaN(suma_exec) && suma_exec != "") {
            pret_pe_km = suma_exec / nr_km;
            pret_pe_km = prepareFloatForUser(pret_pe_km.toFixed(2));
            document.getElementById('pret_pe_km_exec').innerHTML = pret_pe_km;
        }
    }
}

function calc_total_exec() {
    if (document.form1.suma_exec.value == '')
        document.form1.suma_exec.value = '0.00';
    if (document.form1.taxe_supl_from_exec.value == '')
        document.form1.taxe_supl_from_exec.value = '0.00';
    if (document.form1.penaliz_to_exec.value == '')
        document.form1.penaliz_to_exec.value = '0.00';
    var suma_exec = prepareNumberForServer(document.form1.suma_exec.value);
    var taxe_supl_from_exec = prepareNumberForServer(document.form1.taxe_supl_from_exec.value);
    var penaliz_to_exec = prepareNumberForServer(document.form1.penaliz_to_exec.value);
    
    if (!isNaN(suma_exec) && suma_exec != "" && !isNaN(taxe_supl_from_exec) && taxe_supl_from_exec != "" && !isNaN(penaliz_to_exec) && penaliz_to_exec != "")
        document.form1.suma_totala_exec.value = prepareFloatForUser(parseFloat(suma_exec) 
                                                + parseFloat(taxe_supl_from_exec) 
                                                - parseFloat(penaliz_to_exec));              
}

function custom_field_firm(tip) {
	remove_by_ID('notice_msg');
	sndReqNew('modal_custom_fields_firma.php', 'tip='+tip, '', 'displayMessage(response);', 0);	
}

function custom_field_comand(tip) {
	remove_by_ID('notice_msg');
	sndReqNew('modal_custom_fields_comand.php', 'tip='+tip, '', 'displayMessage(response);', 0);	
}

function save_custom_fields_firma(tip_raspuns) {
	var cf = document.getElementById("cf").checked;
	var rc = document.getElementById("rc").checked;
	var tel_fix = document.getElementById("tel_fix").checked;
	var tel_fax = document.getElementById("tel_fax").checked;
	var tel_mobil = document.getElementById("tel_mobil").checked;
	var email = document.getElementById("email").checked;
	var web = document.getElementById("web").checked;

	var tip = document.getElementById("tip").checked;	
	var tara = document.getElementById("tara").checked;	
	var oras = document.getElementById("oras").checked;										
	var calitate_firma = document.getElementById("calitate_firma").checked;
	
	if (tip_raspuns == 'save_render') {
		var per_pag = document.getElementById('per_pag').value;
		var pagina = document.getElementById('pagina').value;
		var tip_firma = document.getElementById('tip_firma_f').value;
		var camp = document.getElementById('camp').value;						
		var camp_order = document.getElementById('camp_order').value;						
		var order = document.getElementById('order').value;						
		var keyword = document.getElementById('keyword').value;	
		var id_client = document.getElementById('id_client').value;	
		if (order == 'ASC') order = 'DESC'; else order = 'ASC';
		//trebuie pastrata ordinea de sortare a coloanei care a fost apasata... eu transmit inversul lui order! si atunci il schimb aici!!
		closeMessage();
		clearCacheNow();		
		sndReqNew('AJAX_proxy.php', 'f=custom_field_firma_render&tip='+tip+'&tara='+tara+'&oras='+oras+'&cf='+cf+'&rc='+rc+'&tel_fix='+tel_fix+'&tel_fax='+tel_fax+'&tel_mobil='+tel_mobil+'&email='+email+'&web='+web+'&id_client='+id_client+'&per_pag='+per_pag+'&pagina='+pagina+'&tip_firma='+tip_firma+'&camp='+camp+'&camp_order='+camp_order+'&order='+order+'&keyword='+keyword+'&calitate_firma='+calitate_firma, 'content_firme', '', 0);
	}	
	
	if (tip_raspuns == 'save') {
		closeMessage();
		sndReqNew('AJAX_proxy.php', 'f=custom_field_firma&tip='+tip+'&tara='+tara+'&oras='+oras+'&cf='+cf+'&rc='+rc+'&tel_fix='+tel_fix+'&tel_fax='+tel_fax+'&tel_mobil='+tel_mobil+'&email='+email+'&web='+web+'&calitate_firma='+calitate_firma, '', '', 0);	
	}
	
}

function save_custom_fields_comand(tip_raspuns) {
    par = document.getElementById('DHTMLSuite_modalBox_contentDiv');
    inputs = par.getElementsByTagName("input");	
    var buffer_id = [];
    var buffer_value = [];
    var cel_putin_una = 0;
    for (i = 0; i < inputs.length; i++) {
        if (inputs[i].id != '') {
            buffer_id[i] = inputs[i].id;
            buffer_value[i] = inputs[i].checked;
            if (buffer_value[i] == true) cel_putin_una = 1;        
        }
    }

    //trebuie sa verific ca cel putin un camp sa fie bifat! 	
    if (!cel_putin_una) alert(Lang_cel_putin_una_selectata)
    else {
        closeMessage();
        if (tip_raspuns == 'save_render') {        
	        //acum salvez in bd noul profile dar si afisez!
	        	
			var per_pag = document.getElementById('per_pag').value;	
			var pagina = document.getElementById('pagina').value;
			var order = document.getElementById('order_sort').value;	
					
			var comanda_incasata = document.getElementById('comanda_incasata').value;
			var comanda_platita = document.getElementById('comanda_platita').value;		
			var scadenta_incasare = document.getElementById('scadenta_incasare').value;		
			var scadenta_plata = document.getElementById('scadenta_plata').value;		
			var f_sol = document.getElementById('f_sol').value;		
			var f_exec = document.getElementById('f_exec').value;				
			var keyword = document.getElementById('keyword').value;
			var camp = document.getElementById('camp').value;
			var camp_sort = document.getElementById('camp_sort').value;
								
			var val1 = document.getElementById('val1_1').value;		
			var val2 = document.getElementById('val2_2').value;		
			var pret_min = document.getElementById('pret_min').value;
			var f_sol = document.getElementById('f_sol').value;
			var f_exec = document.getElementById('f_exec').value;		
			var pret_max = document.getElementById('pret_max').value;		
			var cost_min = document.getElementById('cost_min').value;		
			var cost_max = document.getElementById('cost_max').value;		
			var data_scadenta_sol1 = document.getElementById('data_scadenta_sol1').value;		
			var data_scadenta_sol2 = document.getElementById('data_scadenta_sol2').value;		
			var data_scadenta_exec1 = document.getElementById('data_scadenta_exec1').value;		
			var data_scadenta_exec2 = document.getElementById('data_scadenta_exec2').value;		
			var data_factura_sol1 = document.getElementById('data_factura_sol1').value;		
			var data_factura_sol2 = document.getElementById('data_factura_sol2').value;		
			var data_factura_exec1 = document.getElementById('data_factura_exec1').value;		
			var data_factura_exec2 = document.getElementById('data_factura_exec2').value;		
		
			var sc_incasare = document.getElementById('sc_incasare').value;		
			var sc_plata = document.getElementById('sc_plata').value;		
			var cond_firme = document.getElementById('cond_firme').value;										
	        
	        //if (order == 'ASC') order = 'DESC'; else order = 'ASC';
	        url = 'f=custom_field_comand&tip_raspuns=save_render&per_pag='+per_pag+'&pagina='+pagina+'&comanda_incasata='+comanda_incasata+'&comanda_platita='+comanda_platita+'&scadenta_incasare='+scadenta_incasare+'&scadenta_plata='+scadenta_plata+'&f_sol='+f_sol+'&f_exec='+f_exec+'&camp='+camp+'&order='+order+'&keyword='+keyword+'&val1='+val1+'&val2='+val2+'&pret_min='+pret_min+'&f_sol='+f_sol+'&f_exec='+f_exec+'&pret_max='+pret_max+'&cost_min='+cost_min+'&cost_max='+cost_max+'&data_scadenta_sol1='+data_scadenta_sol1+'&data_scadenta_sol2='+data_scadenta_sol2+'&data_scadenta_exec1='+data_scadenta_exec1+'&data_scadenta_exec2='+data_scadenta_exec2+'&data_factura_sol1='+data_factura_sol1+'&data_factura_sol2='+data_factura_sol2+'&data_factura_exec1='+data_factura_exec1+'&data_factura_exec2='+data_factura_exec2+'&sc_incasare='+sc_incasare+'&sc_plata='+sc_plata+'&cond_firme='+cond_firme+'&camp_sort='+camp_sort;
	        
	        for (i = 0; i < inputs.length; i++) {
	            url += '&' + buffer_id[i] + '=' + buffer_value[i];    
	        }
			clearCacheNow();        
			
	        sndReqNew('AJAX_proxy.php', url, 'pag_and_content', '', 1);        
        }    
        if (tip_raspuns == 'save') {
	        url = 'f=custom_field_comand&tip_raspuns=save';
	        
	        for (i = 0; i < inputs.length; i++) {
	            url += '&' + buffer_id[i] + '=' + buffer_value[i];    
	        }
			clearCacheNow();        
			
	        sndReqNew('AJAX_proxy.php', url, '', '', 1);                
        }        
    }
}

function show_pret_per_month(value) {    
	
	var spanid = document.getElementById('pret_per_month');
	var spanid_total = document.getElementById('pret_total');
	var total_reducere = document.getElementById('total_reducere');
	var pret_total_reducere = document.getElementById('pret_total_reducere');
	var ciclu_plata_sel = document.getElementById("ciclu_plata");		
	var ciclu_plata = ciclu_plata_sel.options[ciclu_plata_sel.selectedIndex].value;
    var discount = 0;
        
	if (value == 0) {
		spanid.innerHTML = CT_PRET_ABON_TIP_1 + ' RON' + ' / ' + Lang_Month;        
		if (ciclu_plata == 0) {
			discount = 0;
			spanid_total.innerHTML = (3 * CT_PRET_ABON_TIP_1) + ' RON';
		}
		if (ciclu_plata == 1) {
			discount = CT_PRET_ABON_TIP_1 / 2;
			spanid_total.innerHTML = (6 * CT_PRET_ABON_TIP_1)  + ' RON';
		}
		if (ciclu_plata == 2) {
			discount = CT_PRET_ABON_TIP_1 * 2;
			spanid_total.innerHTML = (12 * CT_PRET_ABON_TIP_1)  + ' RON';
		}
	}
	if (value == 1) {
	
		spanid.innerHTML = CT_PRET_ABON_TIP_2 + ' RON' + ' / ' + Lang_Month;
		if (ciclu_plata == 0) {
			discount = 0;
			spanid_total.innerHTML = (3 * CT_PRET_ABON_TIP_2)  + ' RON';
		}
		if (ciclu_plata == 1) {
			discount = CT_PRET_ABON_TIP_2 / 2;
			spanid_total.innerHTML = (6 * CT_PRET_ABON_TIP_2)  + ' RON';
		}
		if (ciclu_plata == 2) {
			discount = CT_PRET_ABON_TIP_2 * 2;
			spanid_total.innerHTML = (12 * CT_PRET_ABON_TIP_2)  + ' RON';
		}				
	}
	if (value == 2) {
		spanid.innerHTML = CT_PRET_ABON_TIP_3 + ' RON' + ' / ' + Lang_Month;
		if (ciclu_plata == 0) {
			discount = 0;
			spanid_total.innerHTML = (3 * CT_PRET_ABON_TIP_3)  + ' RON';
		}
		if (ciclu_plata == 1) {
			discount = CT_PRET_ABON_TIP_3 / 2;
			spanid_total.innerHTML = (6 * CT_PRET_ABON_TIP_3)  + ' RON';
		}
		if (ciclu_plata == 2) {
			discount = CT_PRET_ABON_TIP_3 * 2;
			spanid_total.innerHTML = (12 * CT_PRET_ABON_TIP_3)  + ' RON';
		}		
	}
	
	//if (value == 0) spanid_total.innerHTML = (CT_PRET_ABON_TIP_1 * 3) + ' EUR';			
	//if (value == 1) spanid_total.innerHTML = (CT_PRET_ABON_TIP_1 * 6 - discount) +  ' EUR';
	//if (value == 2) spanid_total.innerHTML = (10 * CT_PRET_ABON_TIP_1) + ' EUR';
	
	total_reducere.innerHTML = discount + ' RON';
	
	pret_total_reducere.innerHTML = parseInt(spanid_total.innerHTML) - discount + ' RON';
}

function show_pret_total(value) {
		
	var spanid = document.getElementById('pret_total');
	var pret_total_reducere = document.getElementById('pret_total_reducere');
	var pret_abonament_sel = document.getElementById("tip_abonament");	
	var discount = 0;
	var pret_abonament = pret_abonament_sel.options[pret_abonament_sel.selectedIndex].value;
    if (pret_abonament == 0) pret_abonament = CT_PRET_ABON_TIP_1;
    if (pret_abonament == 1) pret_abonament = CT_PRET_ABON_TIP_2;
    if (pret_abonament == 2) pret_abonament = CT_PRET_ABON_TIP_3;
    
	if (value == 0) {
		spanid.innerHTML = pret_abonament * 3 + ' RON';
		discount = 0;
	}
	if (value == 1) {
		spanid.innerHTML = (pret_abonament * 6 ) +  ' RON';
		discount = pret_abonament / 2;
	}
	if (value == 2) {
		spanid.innerHTML = (12 * pret_abonament) + ' RON';
		discount = pret_abonament * 2;
	}
	var total_reducere = document.getElementById('total_reducere');
	total_reducere.innerHTML = discount + ' RON';
	pret_total_reducere.innerHTML = parseInt(spanid.innerHTML) - discount + ' RON';
}

function check_f_sol(unde) {
	var f_sol_sel = document.getElementById("f_sol_sel");
	var f_sol = f_sol_sel.options[f_sol_sel.selectedIndex].value;	

	var logic_sel = document.getElementById("sau_si");
	var logic = logic_sel.options[logic_sel.selectedIndex].value;	
	
	var f_exec_sel = document.getElementById("f_exec_sel");
	var f_exec = f_exec_sel.options[f_exec_sel.selectedIndex].value;	
	
	if (logic == 'AND') {
		if (f_sol == f_exec) {
			alert(Lang_Error_filtru_comenzi);
			if (unde == 0) f_sol_sel.selectedIndex = 0;
			if (unde == 1) logic_sel.selectedIndex = 0;
			if (unde == 2) f_exec_sel.selectedIndex = 0;
		}
	}
}

function cancel(pagina) {
	window.location.href = pagina;	
}

function close_cautare_avansata() {
	closeMessage();
}

function view_incasari() {
    //comportament detemrinist... suntem siguri ca comenzi_indici are doar un element
    //get the number of the command (nr_comanda_exec)
    
    var element_id = "nr_comanda_exec" + comenzi_indici[0];
    var nr_comanda_exec = document.getElementById(element_id).value;
    document.location.href="view_incasare.php?numar_comanda=" + nr_comanda_exec;
}

function viewplati() {
    //comportament detemrinist... suntem siguri ca comenzi_indici are doar un element
    //get the number of the command (nr_comanda_exec)
    
    var element_id = "nr_comanda_exec" + comenzi_indici[0];
    var nr_comanda_exec = document.getElementById(element_id).value;
	document.location.href="view_plata.php?numar_comanda=" + nr_comanda_exec;
}

function plati_list() {
	window.location.href = 'view_plata.php';
}

function incasari_list() {
	window.location.href = 'view_incasare.php';
}

function go_to_page_firme(per_pag, id_rezultat, id_client, camp, order, nr_pagini_total, keyword) {
	remove_by_ID('notice_msg');
	var x = document.getElementById('page_nr').value;

	var tip_firma = document.getElementById('tip_firma_f').value;
	var camp_order = document.getElementById('camp_order').value;	
	
	if (x <= 0 || x > nr_pagini_total) {
		alert(Lang_page_error);
	}
	else {
		x = x - 1;
		arata_firme_pag(x, per_pag, id_rezultat, id_client, keyword, camp, order, camp_order, tip_firma);
	}
}

function go_to_page_comenzi(per_pag, id_rezultat, id_client, comanda_incasata, comanda_platita, scadenta_incasare, scadenta_plata, f_sol, f_exec, keyword, val1, val2, camp, order, nr_pagini_total, pret_min, pret_max, cost_min, cost_max, data_scadenta_sol1, data_scadenta_sol2, data_scadenta_exec1, data_scadenta_exec2, data_factura_sol1, data_factura_sol2, data_factura_exec1, data_factura_exec2, sc_incasare, sc_plata, cond_firme) {
	remove_by_ID('notice_msg');
	var x = document.getElementById('page_nr').value;
	
	if (x <= 0 || x > nr_pagini_total) {
		alert(Lang_page_error);
	}
	else {
		x--;
		arata_comenzi_pag(x, per_pag, id_rezultat, id_client, comanda_incasata, comanda_platita, scadenta_incasare, scadenta_plata, f_sol, f_exec, keyword, val1, val2, camp, order, pret_min, pret_max, cost_min, cost_max, data_scadenta_sol1, data_scadenta_sol2, data_scadenta_exec1, data_scadenta_exec2, data_factura_sol1, data_factura_sol2, data_factura_exec1, data_factura_exec2, sc_incasare, sc_plata, cond_firme);
	}
}

// TODO:
function prepareFloatForUser(number) {  
    var number2 = number.toString();   
    number2 = number2.replace('.', ',');
    var aux;
    var pos;
    var returnNumber;
    aux = number2.indexOf(',');
    if (aux == -1)
        pos = number2.length;
    else
        pos = aux;            

    returnNumber = number2.substr(pos, number2.length - pos);
    if (returnNumber == '')
        returnNumber = ',00';
    var j = 0;
    var i = 0;
    for (i = pos - 1; i >= 0; i--) {
        aux = number2.charAt(i);
        returnNumber = aux + returnNumber;
        j++;
        if (j % 3 == 0 && i > 0)
            returnNumber = '.' + returnNumber;
    }
    return returnNumber;
}            

function prepareIntForUser(number) {    
    var number2 = number.toString();
    var i = 0;
    var aux;
    var returnNumber;
    var j = 0;
    for (i = number2.length - 1; i >= 0; i--) {
        aux = number2.charAt(i);          
        returnNumber = aux + returnNumber;
        j++;
        if (j % 3 == 0 && i > 0)
            returnNumber = '.' + returnNumber;
    }
    return returnNumber;
}                                                  

function prepareNumberForServer(number) {
    number = number.replace('.', '');
    number = number.replace(',', '.');       
    return number;
}

function calc_data_scadenta_sol() {
    var dateSeparator = '-';
    var data_tr_acte_sol = document.form1.data_tr_acte_sol.value;
    var zile_scadenta_sol = prepareNumberForServer(document.form1.zile_scadenta_sol.value);
    
    var nr = parseInt(zile_scadenta_sol);
    
    if (data_tr_acte_sol.length > 0 && zile_scadenta_sol.length > 0 && !isNaN(nr)) {
        var temp = new Array();
        temp = data_tr_acte_sol.split(dateSeparator);
    
        var myDate=new Date();
        myDate.setFullYear(temp[2],temp[1]-1,temp[0]);
    
        var d = new Date();
        d.setDate(myDate.getDate() + nr);
        var luna = d.getMonth();
        if (luna < 10)
            luna = '0' + luna.toString();
        var zi = d.getDate();
        if (zi < 10)
            zi = '0' + zi.toString();
        document.form1.data_scadenta_sol.value = zi+dateSeparator+luna+dateSeparator+d.getFullYear();
    }
}

function calc_data_scadenta_exec() {
    var dateSeparator = '-';
    var data_primirii_acte_exec = document.form1.data_primirii_acte_exec.value;
    var zile_scadenta_exec = prepareNumberForServer(document.form1.zile_scadenta_exec.value);
    
    var nr = parseInt(zile_scadenta_exec);
    
    if (data_primirii_acte_exec.length > 0 && zile_scadenta_exec.length > 0 && !isNaN(nr)) {
        var temp = new Array();
        temp = data_primirii_acte_exec.split(dateSeparator);
    
        var myDate=new Date();
        myDate.setFullYear(temp[2],temp[1]-1,temp[0]);
    
        var d = new Date();
        d.setDate(myDate.getDate() + nr);
        var luna = d.getMonth();
        if (luna < 10)
            luna = '0' + luna.toString();
        var zi = d.getDate();
        if (zi < 10)
            zi = '0' + zi.toString();
        document.form1.data_scadenta_exec.value = zi+dateSeparator+luna+dateSeparator+d.getFullYear();
    }
}

function cauta_contact(pagina) { 
    var keyword = document.getElementById('keyword').value;    
    var camp_sel = document.getElementById("camp_search");
    var camp = camp_sel.options[camp_sel.selectedIndex].value;
    
    var per_page_sel = document.getElementById("per_page");
    var per_page = per_page_sel.options[per_page_sel.selectedIndex].value;
    
    sndReqNew('AJAX_proxy.php', 'f=cauta_contact_firma&pagina=' + pagina + '&keyword=' + keyword + '&camp=' + camp + '&per_page=' + per_page, 'raspunss', '', 1);               
}

function arata_plati_client(id_client, pagina, per_pag, id_continut) {
    sndReqNew('AJAX_proxy.php',"f=arata_plati_client&id_client="+id_client+'&pagina='+pagina+'&per_pag='+per_pag, id_continut, '', 0);    
}

function ver_trans_cl() {
	var cl_sel = document.getElementById("cl");
	var cl = cl_sel.options[cl_sel.selectedIndex].value;

	var tr_sel = document.getElementById("tr");
	var tr = tr_sel.options[tr_sel.selectedIndex].value;	
	
	if (tr == cl && cl != -1 && tr != -1) {
		alert(Lang_Tr_Cl_Stats_Egal);
		return 1;
	}
	else return 0;
}

function show_stats() {
	//verific daca data personalizata este ok...adica nu cumva data1 sa fie mai in viitor 
	//decat data2
	var data1 = document.getElementById('data1').value;
	data1 = getDateFromText(data1);
	var data2 = document.getElementById('data2').value;
	data2 = getDateFromText(data2);
	if (data1 > data2) {
		alert(LANG_Data_personalizata_wrong);
	    return false;
	}
	
	if (ver_trans_cl() == 0) document.forms.statss.submit();
}

function schimba_monede(moneda) {
	var text = '';
	for (i = 0; i < monede.length; i++) {
		if (moneda != monede[i]) {
			text = text + '1 ' + moneda + ' = <input type="text" size="8" id="' + monede[i]+ '" value="1" name="' + monede[i] + '" /> ' + monede[i] + ', ';
		}
	}
		
	if (text.charAt(text.length - 2) == ',') text = text.substring(0, text.length - 2);
	document.getElementById('tip_moneda').innerHTML = text;
}

function modifica_camp_cautare_firme(value) {
	var search_area = document.getElementById('search_area');
	if (value.charAt(0) == '1') {
		if (value.substring(1, 5) == 'rute') {
			var text = LANG_Loc1 + " " + '<input type="text" name="val1" id="val1" /> '; 
			text += LANG_Loc2 + " " + '<input type="text" name="val2" id="val2" /> ';
			search_area.innerHTML = text;
		}
	}
	else search_area.innerHTML = '<input type="text" name="keyword_kk" id="keyword_kk" onkeypress="onEnter(event, \'firme\');" /> ';
}

function modifica_camp(value, loc) {
	var text;
	if (loc == 'cautare_avansata')
		var spancontainer = document.getElementById('campuri2');
	else 
		var spancontainer = document.getElementById('campuri');

	if (value.charAt(0) == '1') {		
		//trebuie sa vedem daca e data... daca e data punem si butonul de calendar sa poate alege frumos
		//determinam daca e data daca primele 4 litere dupa cifra 1 sunta "data"
		
		if (loc == 'cautare_avansata')
			var camp_filtru_sel = document.getElementById("camp2");
		else
			var camp_filtru_sel = document.getElementById("camp_sel");
        var camp_filtru = camp_filtru_sel.options[camp_filtru_sel.selectedIndex].value;

		if (camp_filtru.substring(1, 5) == 'data') {
			text = Lang_intre + ' ';
			text += '<input id="val1" class="input_date" type="text" name="val1" value="" readonly="readonly"/>';
			if (loc == 'cautare_avansata') {			
				text += '<input id="data1_js" type="image" onclick="displayCalendar(document.getElementById(\'val1\'),\'dd-mm-yyyy\',this,true,\'DHTMLSuite_modalBox_contentDiv\', \'\');return false" src="./images/calendar3.gif"/>';
				text += '<input id="" type="image" onclick="document.getElementById(\'val1\').value=\'\'; return false;" src="./images/deleteButton.gif"/>';				
			}
			else {
				text += '<input id="data1_js" type="image" onclick="displayCalendar(document.getElementById(\'val1\'),\'dd-mm-yyyy\',this,true,\'main\', \'\');return false" src="./images/calendar3.gif"/>'; 
				text += '<input id="" type="image" onclick="document.getElementById(\'val1\').value=\'\'; return false;" src="./images/deleteButton.gif"/>';
			}
			text += ' ' + Lang_si + ' ';
			if (loc == 'cautare_avansata')
				text += '<input id="val2" class="input_date" type="text" name="val2" value="" readonly="readonly"/>';
			else 
				text += '<input id="val2" class="input_date" type="text" name="val2" value="" readonly="readonly"/>';
			text += '<input id="data2_js" type="image" onclick="displayCalendar(document.getElementById(\'val2\'),\'dd-mm-yyyy\',this,true,\'DHTMLSuite_modalBox_contentDiv\', \'\');return false" src="./images/calendar3.gif"/>';
			text += '<input id="" type="image" onclick="document.getElementById(\'val2\').value=\'\'; return false;" src="./images/deleteButton.gif"/>';						
			spancontainer.innerHTML = text;
		}
		else {
			text = Lang_incarcare + ' <input size="10" type="text" id="val1" value="" /> ' + Lang_descarcare + ' ';
			text = text + '<input  size="10" type="text" id="val2" value="" /> ';
			spancontainer.innerHTML = text;
		}	
	}
	else {				
		spancontainer.innerHTML = '<input type="text" value="" name="keyword" id="keyword" />';
	}
}

function changeCurrencyLabels() {
	var selObj = document.getElementById('moneda');
	var monedaFactura1 = document.getElementById('monedaFactura1');
	var monedaFactura2 = document.getElementById('monedaFactura2');
	
	var selIndex = selObj.selectedIndex;
	monedaFactura1.innerHTML = selObj.options[selIndex].text;
	monedaFactura2.innerHTML = selObj.options[selIndex].text;
}

function schimbaMonedaFacturii() {
    var moneda = document.getElementById("moneda").value;
    var moneda_comanda = document.getElementById("moneda_comanda").innerHTML;
    
    if (moneda == moneda_comanda) {
        document.getElementById("curs").value = '';
        document.getElementById("curs").disabled = true;
        document.getElementById("curs_invers").value = '';
        document.getElementById("curs_invers").disabled = true;
    }
    else {
        document.getElementById("curs").disabled = false;
        document.getElementById("curs_invers").disabled = false;
    }
}

function print_factura(index, print) {
	var id = index;
	var curs = document.getElementById("curs").value;
	var curs_invers = document.getElementById("curs_invers").value;
    var sel_moneda = document.getElementById("moneda");
    var moneda = sel_moneda.options[sel_moneda.selectedIndex].value;
    
	var moneda_comanda = document.getElementById("moneda_comanda").innerHTML;
    var text_factura = document.getElementById("text_factura").value;
    var serie_factura = document.getElementById("serie_factura").value;
    var nume_delegat = document.getElementById("nume_delegat").value;
    var mijloc_transport = document.getElementById("mijloc_transport").value;
    var cnp = document.getElementById("cnp").value;
	var serie_ci = document.getElementById("serie_ci").value;
	var tva_inclus = "";
	
    var t1 = '';
    t1 = document.getElementById("t1").checked;
	if (t1 == true)
		tva_inclus = 1;
    else
        tva_inclus = 0;
	
	var tva = document.getElementById("tva").value;
	
	// Fa campurile albe din nou  
    document.getElementById('td_moneda_comanda').className = '';
    document.getElementById('td_moneda_factura').className = '';
    document.getElementById('td_curs').className = '';
    document.getElementById('td_curs_invers').className = '';
    document.getElementById('td_text_factura').className = '';
    document.getElementById('td_serie_factura').className = '';
    document.getElementById('td_tva_inclus').className = '';
    document.getElementById('td_tva').className = '';
    document.getElementById('td_nume_delegat').className = '';
    document.getElementById('td_mijloc_transport').className = '';
    document.getElementById('td_cnp').className = '';
    document.getElementById('td_serie_ci').className = '';
	
    var param_redirect = '';
    var param_save_all = '';
    
    if (print == true) {
        param_redirect = "closeMessage(); document.location='printFactura.php?id="+id+"'";
        param_save_all = '&saveAll=false';
    }
    else {
        param_redirect = 'closeMessage();';
        param_save_all = '&saveAll=true';
    }
    
	sndReqNew('AJAX_proxy.php', 'f=ajax_print_factura'+param_save_all+'&id='+id+"&moneda_comanda="+moneda_comanda+"&moneda="+moneda+"&curs="+curs+"&curs_invers="+curs_invers
    +"&text_factura="+text_factura+"&serie_factura="+serie_factura+"&tva_inclus="+tva_inclus+"&tva="+tva+"&nume_delegat="+nume_delegat
    +"&mijloc_transport="+mijloc_transport+"&cnp="+cnp+"&serie_ci="+serie_ci
    ,'',param_redirect, 0);
}


/*******************************************************************/
/*																   */
/*							VALIDATIONS							   */
/*																   */
/*******************************************************************/


function validateMail(str, mandatory){
  if (str.length == 0) {
    if (mandatory == true) {
      alert(LANG_is_mandatory + ' ' + LANG_email)
      return (false)
    }
    else return (true)
  }
  var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i
  if (filter.test(str))
    return (true)
  else{
    alert(LANG_invalid_mail)
    return (false)
  }
}

//testeaza str sa fie alfanumeric, sa fie de minim len caractere
//fieldname este numele campului testat (folosit pt alert)
function validateAlphanum(str, fieldname, mandatory, len) {
  if (str.length == 0) {
    if (mandatory == true) {
      alert(LANG_is_mandatory + ' ' + fieldname)
      return (false)
    }
    else return (true)
  }
  if (str.length <len) {
    alert(fieldname + ' ' + LANG_has_to_be_at_least + len + LANG_long)
    return (false)
  }
  var filter=/^[a-zA-Z0-9]+(\s[a-zA-Z?-?0-9]+)*$/  
  if (filter.test(str))
    return (true)
  else{
    alert(fieldname + ' ' + LANG_must_alphanum)
    return (false)
  }
}

function validatePrintable(str, fieldname, mandatory, len) {
  if (str.length == 0) {
    if (mandatory == true) {
      alert(LANG_is_mandatory + fieldname)
      return (false)
    }
    else return (true)
  }
  if (str.length <len) {
    alert(fieldname + ' ' + LANG_has_to_be_at_least + len + LANG_long)
    return (false)
  }  
  var filter=/^[\w\s?-?.,:&;'!?<>//=()-]*$/
  if (filter.test(str))
    return (true)
  else{
    alert(fieldname + ' ' + LANG_must_printable)
    return (false)
  }
}

//testeaza str sa fie alfanumeric, sa fie de minim len caractere
//fieldname este numele campului testat (folosit pt alert)
function validateAlphaSpaces(str, fieldname, mandatory, len) {
  if (str.length == 0) {
    if (mandatory == true) {
      alert(LANG_is_mandatory + ' ' + fieldname)
      return (false)
    }
    else return (true)
  }
  if (str.length <len) {
    alert(fieldname + ' ' + LANG_has_to_be_at_least + len + LANG_long)
    return (false)
  }
  var filter=/^[a-zA-Z]+(\s[a-zA-Z?-?]+)*$/
  if (filter.test(str))
    return (true)
  else{
    alert(fieldname + ' ' + LANG_must_alpha_spaces)
    return (false)
  }
}

function validateName(str, fieldname, mandatory, len) {
  if (str.length == 0) {
    if (mandatory == true) {
      alert(LANG_is_mandatory + ' ' + fieldname)
      return (false)
    }
    else return (true)
  }
  if (str.length <len) {
    alert(fieldname + ' ' + LANG_has_to_be_at_least + len + LANG_long)
    return (false)
  }
  var filter=/^[\w\s?-?.'-]*$/
  if (filter.test(str))
    return (true)
  else{
    alert(fieldname + ' ' + LANG_must_name)
    return (false)
  }
}

function validateUsername(str, len) {
  var filter=/^([\w]+(?:\.[\w]+)*)$/
  if (str.length <len) {
    alert(LANG_username + ' ' + LANG_has_to_be_at_least + len + LANG_long)
    return (false)
  }
  if (filter.test(str))
    return (true)
  else{
    alert(LANG_invalid_username)
    return (false)
  }
}

function validatePosInteger(str, fieldname, mandatory) {
  if (str.length == 0) {
    if (mandatory == true) {
      alert(LANG_is_mandatory + ' ' + fieldname)
      return (false)
    }
    else return (true)
  }
  var filter=/^\d+$/
  if (filter.test(str))
    return (true)
  else{
    alert(fieldname + ' ' + LANG_must_pos_int)
    return (false)
  }
}

function validateInteger(str, fieldname, mandatory) {
  if (str.length == 0) {
    if (mandatory == true) {
      alert(LANG_is_mandatory + ' ' + fieldname)
      return (false)
    }
    else return (true)
  }
  var filter=/^[+-]?(\d)+$/
  if (filter.test(str))
    return (true)
  else{
    alert(fieldname + ' ' + LANG_must_int)
    return (false)
  }
}

function validateFloat(str, fieldname, mandatory) {
  if (str.length == 0) {
    if (mandatory == true) {
      alert(LANG_is_mandatory + fieldname)
      return (false)
    }
    else return (true)
  }
  var filter=/^[0-9]+([\.|,][0-9]+)?$/
  if (filter.test(str))
    return (true)
  else{
    alert(fieldname + ' ' + LANG_must_float)
    return (false)
  }
}

function checkTheSame(str1,str2) {
  if (str1 == str2)
    return (true)
  else {
    alert(LANG_pass_dont_match);
    return (false)
  }
}

//testeaza str sa fie alfanumeric, sa fie de minim len caractere
//fieldname este numele campului testat (folosit pt alert)
function validateFilename(str, len, fieldname) {
  
  if (str.length <len) {
    alert(fieldname + ' ' + LANG_has_to_be_at_least + len + LANG_long)
    return (false)
  }
  return (true);
  /*if (filter.test(str))
    return (true)
  else{
    alert(fieldname + LANG_must_filename)
    return (false)*/
}

function validateNotEmpty(str, fieldname) {
  if (str.length <= 0) {
    alert(LANG_is_mandatory + ' ' + fieldname)
    return (false)
  }
  return (true)
}

function validatePhone(str, mandatory, fieldname) {
  if (str.length == 0) {
    if (mandatory == true) {  
      alert(LANG_is_mandatory + ' ' + fieldname)
      return (false)
    }
    else return (true)
  }
  var filter=/^(\+)?[\d]+([\s./-]*[\d]+)*$/
  if (filter.test(str))
    return (true)
  else{
    alert(fieldname + ' ' + LANG_must_phone)
    return (false)
  }
}

function validateSite(str, mandatory, fieldname) {
  if (str.length == 0) {
    if (mandatory == true) {  
      alert(LANG_is_mandatory + ' ' + fieldname)
      return (false)
    }
    else return (true)
  }
  var filter=/^[\w-]+(.[\w-]+)*$/ /*/^([a-z]+:(/)(/))?[\w-]+(.[\w-]+)*(:[\d]+)?(/[~\w-])*(/)?$/*/  
  if (filter.test(str))
    return (true)
  else{
    alert(fieldname + ' ' + LANG_must_site)
    return (false)
  }
}

//returns the timestamp of a date, given in the 'DD.MM.YYYY hh.mm' format
function parseDate(str) {
  var datetime=str.split(' ')
  var date=datetime[0].split('.')
  var time=datetime[1].split(':')
  return (new Date(date[2], date[1] - 1, date[0], time[0], time[1])).getTime()
}

function validateDateFuture(str, fieldname) {
  var timestamp = parseDate(str)
  if (timestamp <= (new Date()).getTime()) {
    alert(fieldname + LANG_must_be_future)
    return (false)
  }
  return (true)
}

function validateDateAfter(str, fieldname, str2, fieldname2) {
  var timestamp = parseDate(str)
  var timestamp2 = parseDate(str2)
  if (timestamp <= timestamp2) {
    alert(fieldname + LANG_must_be_after + fieldname2)
    return (false)
  }
  return (true)
}

function checkDate(d,m,y) {
	var yl=1990; // least year to consider
	var ym=2020; // most year to consider
	if (m<1 || m>12) return(false);
	if (d<1 || d>31) return(false);
	if (y<yl || y>ym) return(false);
	if (m==4 || m==6 || m==9 || m==11)
		if (d==31)
			return(false);
	if (m==2) {
		var b=parseInt(y/4);
		if (isNaN(b)) return(false);
		if (d>29) return(false);
		if (d==29 && ((y/4)!=parseInt(y/4))) return(false);
	}
	return(true);
}


/*******************************************************************/
/*																   */
/*							UTILS PLATI							   */
/*																   */
/*******************************************************************/

var nr_comandaORDER = 1;		//desc default! it will complement on first call
var sumaORDER = 1;
var dataORDER = 1;
var nr_comanda_execORDER = 1;
var monedaORDER = 1;
var orderBY = "";				//order for pagination
var orderKIND = 1;				//order KIND for pagination


function renderPlatiPage(tip, pageNumber, perPage, defaultView, orderBY, orderKIND) {
	var options = "";
	
	if (defaultView == 0)
		options = "f=renderPlatiPage&page=" + pageNumber + "&perPage=" + perPage + "&default=" + defaultView + "&tip=" + tip + "&orderby=" + orderBY + "&orderkind=" + orderKIND; 					
	else {
		options = "f=renderPlatiPage&page=" + pageNumber + "&perPage=" + perPage + "&default=" + defaultView + "&tip=" + tip + "&orderby=" + orderBY + "&orderkind=" + orderKIND; 					
		var nr_comanda = document.view_plati.nr_comanda.value;
		var moneda = document.view_plati.moneda.value;
		var suma = document.view_plati.suma.value;
		var data = document.view_plati.data.value;	
		
		if (suma != "")
			options = options + "&suma=" + suma;
		if (moneda != "")
			options = options + "&moneda=" + moneda;
		if (data != "")
			options = options + "&data=" + data;
		if (nr_comanda != "")		
			options = options + "&nr_comanda=" + nr_comanda;	
	}
	sndReqNew("AJAX_proxy.php", options, "platiTable", '', 1);		
}

function sortByHeading(tip, pageNumber, perPage, defaultView, orderBY, orderKIND) {
	var options = "f=renderPlatiPage&page=" + pageNumber + "&perPage=" + perPage;
	//var options = options + "&tip=" + tip + "&default=0";
	options = options + "&tip=" + tip + "&default=" + defaultView;
	
	var nr_comanda = document.view_plati.nr_comanda.value;
	var moneda = document.view_plati.moneda.value;
	var suma = document.view_plati.suma.value;
	var data = document.view_plati.data.value;	
	
	if (suma != "")
		options = options + "&suma=" + suma;
	if (moneda != "")
		options = options + "&moneda=" + moneda;
	if (data != "")
		options = options + "&data=" + data;
	if (nr_comanda != "")		
		options = options + "&nr_comanda=" + nr_comanda;	
	
	if (orderBY == undefined) {
		orderBY = "suma"; //default sorting	
		oderKIND = 0;		
	}
	options = options + "&orderby=" + orderBY + "&orderkind=" + complementORDER(orderBY);
		
	//make the request	
	//here, options is the indexKey	
	sndReqNew("AJAX_proxy.php", options, "platiTable", '', 1);				
}

function complementORDER(orderFIELD) {
	if (orderKIND == 0) orderKIND = 1; else orderKIND = 0;
	if (orderFIELD == "suma") {
		orderBY = orderFIELD;
		if (sumaORDER == 1) sumaORDER = 0;
		else sumaORDER = 1;		
		return sumaORDER;		
	}	
	if (orderFIELD == "data") {
		orderBY = orderFIELD;
		if (dataORDER == 1) dataORDER = 0;
		else dataORDER = 1;
		return dataORDER;		
	}
	if (orderFIELD == "moneda") {
		orderBY = orderFIELD;
		if (monedaORDER == 1) monedaORDER = 0;
		else monedaORDER = 1;
		return monedaORDER;		
	}
	if (orderFIELD == "nr_comanda_exec") {
		orderBY = orderFIELD;
		if (nr_comanda_execORDER == 1) nr_comanda_execORDER = 0;
		else nr_comanda_execORDER = 1;
		return nr_comanda_execORDER;		
	}
}

function filterPlati(tip, pageNumber, perPage, orderBY, orderKIND) {	
	//get parameters
	var nr_comanda = document.view_plati.nr_comanda.value;
	var moneda = document.view_plati.moneda.value;
	var suma = document.view_plati.suma.value;
	var data = document.view_plati.data.value;	
	//form the string URL
	var options = "f=renderPlatiPage&page=" + pageNumber + "&perPage=" + perPage;
	if (moneda != "")
		options = options + "&moneda=" + moneda;
	if (suma != "")
		options = options + "&suma=" + suma;
	if (data != "")
		options = options + "&data=" + data;
	if (nr_comanda != "")		
		options = options + "&nr_comanda=" + nr_comanda;
		
	if (orderBY == undefined) {
		orderBY = "suma"; //default sorting	
		oderKIND = 0;		
	}
    
    options = options + "&tip=" + tip + "&default=1";
	options = options + "&orderby=" + orderBY + "&orderkind=" + orderKIND;
	
	//make the request	
	//here, options is the indexKey	
	sndReqNew("AJAX_proxy.php", options, "platiTable", '', 1);		
}

function deleteFilter(tip, pageNumber, perPage) {
	document.view_plati.nr_comanda.value = "";	
	document.view_plati.suma.value = "";
	document.view_plati.data.value = "";	
		
	renderPlatiPage(tip, pageNumber, perPage, '0', "suma", "1");	
}

function editPlata(idPLata) {
	document.location = "add_plata.php?tip=1&idPlata=" + idPLata;
}


function editIncasare(idPLata) {
	document.location = "add_plata.php?tip=0&idPlata=" + idPLata;
}

function deletePlata(id, defaultView, pageNumber, perPage, tip, numarComanda) {
	var raspuns = confirm("Doriti sa stergeti plata?");
	if (raspuns) {		
		//flush the cache
		clearCacheNow();
		//end flush the cache
		options="f=deletePlata&id=" + id + "&default=" + defaultView + "&pageNumber=" + pageNumber + "&perPage=" + perPage + "&tip=" + tip + "&numar_comanda=" + numarComanda;
		sndReqNew("AJAX_proxy.php", options, "platiTable", '', 0);		
	}
}

function view_comanda() {
	document.location.href="show_comenzi.php";
}

function gotoPage(pageNo, totalPages) {    
    if (validatePosInteger(pageNo, "Pagina", true))
        if (pageNo <= totalPages && pageNo > 0)
            return true;
        else {
            alert(Lang_page_error);
            return false;
        }
}

/*******************************************************************/
/*																   */
/*							AJAX								   */
/*																   */
/*******************************************************************/

//Creates an AJAX internal used object
function createRequestObject() {
    var ro;
    var browser = navigator.appName;
    if( browser == "Microsoft Internet Explorer"){
        ro = new ActiveXObject("Microsoft.XMLHTTP");
    }
    else {
        ro = new XMLHttpRequest();
    }
    return ro;
}

var httpNew = createRequestObject();
var cacheArray = [];

function clearCacheNow() {
	cacheArray.length = 0;
	cacheArray = [];           
}

function addToCache(script, action, id) {
    var argv = script + '?' + action;
    cacheArray[argv] = document.getElementById(id).innerHTML; 
}

function sndReqNew(script, action, id, toExec, caching) {    

    var argv = script;
    if (action != '')
        argv += '?' + action;
    
    if (caching == 1 && cacheArray[argv] != "" && cacheArray[argv] != undefined) {            
        document.getElementById(id).innerHTML = cacheArray[argv];               
        return;
    }
    
    document.getElementById('main').style.cursor = 'progress';
    
    httpNew.open('get', argv);         /// am scos al doilea parametru de false!!!!
    httpNew.onreadystatechange = function() {

        var notExec = false;
        if (httpNew.readyState == 4) {

            var response = httpNew.responseText; 
            
				// check if there is any message we should display;
				if (response.indexOf('MESSAGE;') != -1) {
                    var temp = new Array();
                    temp = response.split(';');
                    
                    // Recompun raspunsul urmator mesajului;
                    response = '';
                    for (i = 2; i<temp.length - 1; i++) {
						response = response + temp[i];
                    }
                    
                    notExec = true;
                    alert(temp[1]);                        
                }
    
                // check the validation is there
                if (response.indexOf('VALIDATE;') != -1) {
                    var temp = new Array();
                    temp = response.split(';');
                    
                    if (temp.length > 2) {
                        for (i = 1; i < temp.length - 1; i++) {
                            var id_temp = temp[i];            
                            document.getElementById(id_temp).className = 'incorrect';
                        }
                        notExec = true;                        
                    }    
                        
                }
                else
                // check the errors here

                if (response.indexOf('ERROR;') != -1) {

                    var temp = new Array();
                    temp = response.split(';');
                    
                    // Recompun raspunsul urmator mesajului;
                    response = '';
                    for (i = 2; i<temp.length - 1; i++) {
                        response = response + temp[i];
                    }
                    
                    if (temp.length > 1) {
                        // Treat the exception / error
                        alert(Lang_a_fost_o_eroare + "Error number: " + temp[1]);
                        notExec = true;
                    }                
                }
                else {

					// stop displaying for the calls that do not want to
                    if (id != '' && response != '') {
						// caching the response
						if (caching == 1 && cacheArray)
							cacheArray[argv] = response;                                                            
						document.getElementById(id).innerHTML = response;
                    }
                }                
                
            if (toExec != '' && notExec != true) {
                eval(toExec);
            }
        }    
        document.getElementById('main').style.cursor = 'default';
    }
    httpNew.send(null);    
}


/*******************************************************************/
/*																   */
/*							CALENDAR							   */
/*																   */
/*******************************************************************/

/************************************************************************************************************
JS Calendar
Copyright (C) September 2006  DTHMLGoodies.com, Alf Magne Kalleland

This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

Dhtmlgoodies.com., hereby disclaims all copyright interest in this script
written by Alf Magne Kalleland.

Alf Magne Kalleland, 2006
Owner of DHTMLgoodies.com

************************************************************************************************************/

/* Update log:
(C) www.dhtmlgoodies.com, September 2005

Version 1.2, November 8th - 2005 - Added <iframe> background in IE
Version 1.3, November 12th - 2005 - Fixed top bar position in Opera 7
Version 1.4, December 28th - 2005 - Support for Spanish and Portuguese
Version 1.5, January  18th - 2006 - Fixed problem with next-previous buttons after a month has been selected from dropdown
Version 1.6, February 22nd - 2006 - Added variable which holds the path to images.
                                    Format todays date at the bottom by use of the todayStringFormat variable
                                    Pick todays date by clicking on todays date at the bottom of the calendar
Version 2.0     May, 25th - 2006      - Added support for time(hour and minutes) and changing year and hour when holding mouse over + and - options. (i.e. instead of click)
Version 2.1     July, 2nd - 2006      - Added support for more date formats(example: d.m.yyyy, i.e. one letter day and month).

// Modifications by Gregg Buntin
Version 2.1.1 8/9/2007  gfb   - Add switch to turn off Year Span Selection
                                This allows me to only have this year & next year in the drop down
                                     
Version 2.1.2 8/30/2007 gfb  - Add switch to start week on Sunday
                               Add switch to turn off week number display
                               Fix bug when using on an HTTPS page

*/
var turnOffYearSpan = false;     // true = Only show This Year and Next, false = show +/- 5 years
var weekStartsOnSunday = false;  // true = Start the week on Sunday, false = start the week on Monday
var showWeekNumber = true;  // true = show week number,  false = do not show week number

var languageCode = 'en';    // Possible values:     en,ge,no,nl,es,pt-br,fr
                            // en = english, ge = german, no = norwegian,nl = dutch, es = spanish, pt-br = portuguese, fr = french, da = danish, hu = hungarian(Use UTF-8 doctype for hungarian)

var calendar_display_time = true;

// Format of current day at the bottom of the calendar
// [todayString] = the value of todayString
// [dayString] = day of week (examle: mon, tue, wed...)
// [UCFdayString] = day of week (examle: Mon, Tue, Wed...) ( First letter in uppercase)
// [day] = Day of month, 1..31
// [monthString] = Name of current month
// [year] = Current year
var todayStringFormat = '[todayString] [UCFdayString]. [day]. [monthString] [year]';
var pathToImages = 'images/';    // Relative to your HTML file

var speedOfSelectBoxSliding = 200;    // Milliseconds between changing year and hour when holding mouse over "-" and "+" - lower value = faster
var intervalSelectBox_minutes = 5;    // Minute select box - interval between each option (5 = default)

var calendar_offsetTop = 0;        // Offset - calendar placement - You probably have to modify this value if you're not using a strict doctype
var calendar_offsetLeft = 0;    // Offset - calendar placement - You probably have to modify this value if you're not using a strict doctype
var calendarDiv = false;

var MSIE = false;
var Opera = false;
if(navigator.userAgent.indexOf('MSIE')>=0 && navigator.userAgent.indexOf('Opera')<0)MSIE=true;
if(navigator.userAgent.indexOf('Opera')>=0)Opera=true;


switch(languageCode){
    case "en":    /* English */
        var monthArray = ['January','February','March','April','May','June','July','August','September','October','November','December'];
        var monthArrayShort = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
        var dayArray = ['Mon','Tue','Wed','Thu','Fri','Sat','Sun'];
        var weekString = 'Week';
        var todayString = '';
        break;
    case "ge":    /* German */
        var monthArray = ['Januar','Februar','M�rz','April','Mai','Juni','Juli','August','September','Oktober','November','Dezember'];
        var monthArrayShort = ['Jan','Feb','Mar','Apr','Mai','Jun','Jul','Aug','Sep','Okt','Nov','Dez'];
        var dayArray = ['Mon','Die','Mit','Don','Fre','Sam','Son'];
        var weekString = 'Woche';
        var todayString = 'Heute';
        break;
    case "no":    /* Norwegian */
        var monthArray = ['Januar','Februar','Mars','April','Mai','Juni','Juli','August','September','Oktober','November','Desember'];
        var monthArrayShort = ['Jan','Feb','Mar','Apr','Mai','Jun','Jul','Aug','Sep','Okt','Nov','Des'];
        var dayArray = ['Man','Tir','Ons','Tor','Fre','L&oslash;r','S&oslash;n'];
        var weekString = 'Uke';
        var todayString = 'Dagen i dag er';
        break;
    case "nl":    /* Dutch */
        var monthArray = ['Januari','Februari','Maart','April','Mei','Juni','Juli','Augustus','September','Oktober','November','December'];
        var monthArrayShort = ['Jan','Feb','Mar','Apr','Mei','Jun','Jul','Aug','Sep','Okt','Nov','Dec'];
        var dayArray = ['Ma','Di','Wo','Do','Vr','Za','Zo'];
        var weekString = 'Week';
        var todayString = 'Vandaag';
        break;
    case "es": /* Spanish */
        var monthArray = ['Enero','Febrero','Marzo','April','Mayo','Junio','Julio','Agosto','Septiembre','Octubre','Noviembre','Diciembre'];
        var monthArrayShort =['Ene','Feb','Mar','Abr','May','Jun','Jul','Ago','Sep','Oct','Nov','Dic'];
        var dayArray = ['Lun','Mar','Mie','Jue','Vie','Sab','Dom'];
        var weekString = 'Semana';
        var todayString = 'Hoy es';
        break;
    case "pt-br":  /* Brazilian portuguese (pt-br) */
        var monthArray = ['Janeiro','Fevereiro','Mar&ccedil;o','Abril','Maio','Junho','Julho','Agosto','Setembro','Outubro','Novembro','Dezembro'];
        var monthArrayShort = ['Jan','Fev','Mar','Abr','Mai','Jun','Jul','Ago','Set','Out','Nov','Dez'];
        var dayArray = ['Seg','Ter','Qua','Qui','Sex','S&aacute;b','Dom'];
        var weekString = 'Sem.';
        var todayString = 'Hoje &eacute;';
        break;
    case "fr":      /* French */
        var monthArray = ['Janvier','F�vrier','Mars','Avril','Mai','Juin','Juillet','Ao�t','Septembre','Octobre','Novembre','D�cembre'];
        var monthArrayShort = ['Jan','Fev','Mar','Avr','Mai','Jun','Jul','Aou','Sep','Oct','Nov','Dec'];
        var dayArray = ['Lun','Mar','Mer','Jeu','Ven','Sam','Dim'];
        var weekString = 'Sem';
        var todayString = "Aujourd'hui";
        break;
    case "da": /*Danish*/
        var monthArray = ['januar','februar','marts','april','maj','juni','juli','august','september','oktober','november','december'];
        var monthArrayShort = ['jan','feb','mar','apr','maj','jun','jul','aug','sep','okt','nov','dec'];
        var dayArray = ['man','tirs','ons','tors','fre','l&oslash;r','s&oslash;n'];
        var weekString = 'Uge';
        var todayString = 'I dag er den';
        break;
    case "hu":    /* Hungarian  - Remember to use UTF-8 encoding, i.e. the <meta> tag */
        var monthArray = ['Január','Február','Március','�?prilis','Május','Június','Július','Augusztus','Szeptember','Október','November','December'];
        var monthArrayShort = ['Jan','Feb','Márc','�?pr','Máj','Jún','Júl','Aug','Szep','Okt','Nov','Dec'];
        var dayArray = ['Hé','Ke','Sze','Cs','Pé','Szo','Vas'];
        var weekString = 'Hét';
        var todayString = 'Mai nap';
        break;
    case "it":    /* Italian*/
        var monthArray = ['Gennaio','Febbraio','Marzo','Aprile','Maggio','Giugno','Luglio','Agosto','Settembre','Ottobre','Novembre','Dicembre'];
        var monthArrayShort = ['Gen','Feb','Mar','Apr','Mag','Giu','Lugl','Ago','Set','Ott','Nov','Dic'];
        var dayArray = ['Lun',';Mar','Mer','Gio','Ven','Sab','Dom'];
        var weekString = 'Settimana';
        var todayString = 'Oggi &egrave; il';
        break;
    case "sv":    /* Swedish */
        var monthArray = ['Januari','Februari','Mars','April','Maj','Juni','Juli','Augusti','September','Oktober','November','December'];
        var monthArrayShort = ['Jan','Feb','Mar','Apr','Maj','Jun','Jul','Aug','Sep','Okt','Nov','Dec'];
        var dayArray = ['M&aring;n','Tis','Ons','Tor','Fre','L&ouml;r','S&ouml;n'];
        var weekString = 'Vecka';
        var todayString = 'Idag &auml;r det den';
        break;
    case "cz":    /* Czech */
        var monthArray = ['leden','&#250;nor','b&#345;ezen','duben','kv&#283;ten','&#269;erven','&#269;ervenec','srpen','z&#225;&#345;&#237;','&#345;&#237;jen','listopad','prosinec'];
        var monthArrayShort = ['led','&#250;n','b&#345;','dub','kv&#283;','&#269;er','&#269;er-ec','srp','z&#225;&#345;','&#345;&#237;j','list','pros'];
        var dayArray = ['Pon','&#218;t','St','&#268;t','P&#225;','So','Ne'];
        var weekString = 't&#253;den';
        var todayString = '';
        break;    
}

if (weekStartsOnSunday) {
   var tempDayName = dayArray[6];
   for(var theIx = 6; theIx > 0; theIx--) {
      dayArray[theIx] = dayArray[theIx-1];
   }
   dayArray[0] = tempDayName;
}



var daysInMonthArray = [31,28,31,30,31,30,31,31,30,31,30,31];
var currentMonth;
var currentYear;
var currentHour;
var currentMinute;
var calendarContentDiv;
var returnDateTo;
var returnFormat;
var activeSelectBoxMonth;
var activeSelectBoxYear;
var activeSelectBoxHour;
var activeSelectBoxMinute;

var iframeObj = false;
//// fix for EI frame problem on time dropdowns 09/30/2006
var iframeObj2 =false;
function EIS_FIX_EI1(where2fixit)
{

        if(!iframeObj2)return;
        iframeObj2.style.display = 'block';
        iframeObj2.style.height =document.getElementById(where2fixit).offsetHeight+1;
        iframeObj2.style.width=document.getElementById(where2fixit).offsetWidth;
        iframeObj2.style.left=getleftPos(document.getElementById(where2fixit))+1-calendar_offsetLeft;
        iframeObj2.style.top=getTopPos(document.getElementById(where2fixit))-document.getElementById(where2fixit).offsetHeight-calendar_offsetTop;
}

function EIS_Hide_Frame()
{        if(iframeObj2)iframeObj2.style.display = 'none';}
//// fix for EI frame problem on time dropdowns 09/30/2006
var functionToCall;
var returnDateToYear;
var returnDateToMonth;
var returnDateToDay;
var returnDateToHour;
var returnDateToMinute;

var inputYear;
var inputMonth;
var inputDay;
var inputHour;
var inputMinute;
var calendarDisplayTime = false;

var selectBoxHighlightColor = '#D60808'; // Highlight color of select boxes
var selectBoxRolloverBgColor = '#E2EBED'; // Background color on drop down lists(rollover)

var selectBoxMovementInProgress = false;
var activeSelectBox = false;

function cancelCalendarEvent()
{
    return false;
}
function isLeapYear(inputYear)
{
    if(inputYear%400==0||(inputYear%4==0&&inputYear%100!=0)) return true;
    return false;

}
var activeSelectBoxMonth = false;
var activeSelectBoxDirection = false;

function highlightMonthYear()
{
    if(activeSelectBoxMonth)activeSelectBoxMonth.className='';
    activeSelectBox = this;


    if(this.className=='monthYearActive'){
        this.className='';
    }else{
        this.className = 'monthYearActive';
        activeSelectBoxMonth = this;
    }

    if(this.innerHTML.indexOf('-')>=0 || this.innerHTML.indexOf('+')>=0){
        if(this.className=='monthYearActive')
            selectBoxMovementInProgress = true;
        else
            selectBoxMovementInProgress = false;
        if(this.innerHTML.indexOf('-')>=0)activeSelectBoxDirection = -1; else activeSelectBoxDirection = 1;

    }else selectBoxMovementInProgress = false;

}

function showMonthDropDown()
{
    if(document.getElementById('monthDropDown').style.display=='block'){
        document.getElementById('monthDropDown').style.display='none';
        //// fix for EI frame problem on time dropdowns 09/30/2006
                EIS_Hide_Frame();
    }else{
        document.getElementById('monthDropDown').style.display='block';
        document.getElementById('yearDropDown').style.display='none';
        document.getElementById('hourDropDown').style.display='none';
        document.getElementById('minuteDropDown').style.display='none';
            if (MSIE)
        { EIS_FIX_EI1('monthDropDown')}
        //// fix for EI frame problem on time dropdowns 09/30/2006

    }
}

function showYearDropDown()
{
    if(document.getElementById('yearDropDown').style.display=='block'){
        document.getElementById('yearDropDown').style.display='none';
        //// fix for EI frame problem on time dropdowns 09/30/2006
                EIS_Hide_Frame();
    }else{
        document.getElementById('yearDropDown').style.display='block';
        document.getElementById('monthDropDown').style.display='none';
        document.getElementById('hourDropDown').style.display='none';
        document.getElementById('minuteDropDown').style.display='none';
            if (MSIE)
        { EIS_FIX_EI1('yearDropDown')}
        //// fix for EI frame problem on time dropdowns 09/30/2006

    }

}
function showHourDropDown()
{
    if(document.getElementById('hourDropDown').style.display=='block'){
        document.getElementById('hourDropDown').style.display='none';
        //// fix for EI frame problem on time dropdowns 09/30/2006
                EIS_Hide_Frame();
    }else{
        document.getElementById('hourDropDown').style.display='block';
        document.getElementById('monthDropDown').style.display='none';
        document.getElementById('yearDropDown').style.display='none';
        document.getElementById('minuteDropDown').style.display='none';
                if (MSIE)
        { EIS_FIX_EI1('hourDropDown')}
        //// fix for EI frame problem on time dropdowns 09/30/2006
    }

}
function showMinuteDropDown()
{
    if(document.getElementById('minuteDropDown').style.display=='block'){
        document.getElementById('minuteDropDown').style.display='none';
        //// fix for EI frame problem on time dropdowns 09/30/2006
                EIS_Hide_Frame();
    }else{
        document.getElementById('minuteDropDown').style.display='block';
        document.getElementById('monthDropDown').style.display='none';
        document.getElementById('yearDropDown').style.display='none';
        document.getElementById('hourDropDown').style.display='none';
                if (MSIE)
        { EIS_FIX_EI1('minuteDropDown')}
        //// fix for EI frame problem on time dropdowns 09/30/2006
    }
}

function selectMonth()
{
    document.getElementById('calendar_month_txt').innerHTML = this.innerHTML
    currentMonth = this.id.replace(/[^\d]/g,'');

    document.getElementById('monthDropDown').style.display='none';
    //// fix for EI frame problem on time dropdowns 09/30/2006
                EIS_Hide_Frame();
    for(var no=0;no<monthArray.length;no++){
        document.getElementById('monthDiv_'+no).style.color='';
    }
    this.style.color = selectBoxHighlightColor;
    activeSelectBoxMonth = this;
    writeCalendarContent();

}

function selectHour()
{
    document.getElementById('calendar_hour_txt').innerHTML = this.innerHTML
    currentHour = this.innerHTML.replace(/[^\d]/g,'');
    document.getElementById('hourDropDown').style.display='none';
    //// fix for EI frame problem on time dropdowns 09/30/2006
                EIS_Hide_Frame();
    if(activeSelectBoxHour){
        activeSelectBoxHour.style.color='';
    }
    activeSelectBoxHour=this;
    this.style.color = selectBoxHighlightColor;
}

function selectMinute()
{
    document.getElementById('calendar_minute_txt').innerHTML = this.innerHTML
    currentMinute = this.innerHTML.replace(/[^\d]/g,'');
    document.getElementById('minuteDropDown').style.display='none';
    //// fix for EI frame problem on time dropdowns 09/30/2006
                EIS_Hide_Frame();
    if(activeSelectBoxMinute){
        activeSelectBoxMinute.style.color='';
    }
    activeSelectBoxMinute=this;
    this.style.color = selectBoxHighlightColor;
}


function selectYear()
{
    document.getElementById('calendar_year_txt').innerHTML = this.innerHTML
    currentYear = this.innerHTML.replace(/[^\d]/g,'');
    document.getElementById('yearDropDown').style.display='none';
    //// fix for EI frame problem on time dropdowns 09/30/2006
                EIS_Hide_Frame();
    if(activeSelectBoxYear){
        activeSelectBoxYear.style.color='';
    }
    activeSelectBoxYear=this;
    this.style.color = selectBoxHighlightColor;
    writeCalendarContent();

}

function switchMonth()
{
    if(this.src.indexOf('left')>=0){
        currentMonth=currentMonth-1;;
        if(currentMonth<0){
            currentMonth=11;
            currentYear=currentYear-1;
        }
    }else{
        currentMonth=currentMonth+1;;
        if(currentMonth>11){
            currentMonth=0;
            currentYear=currentYear/1+1;
        }
    }

    writeCalendarContent();


}

function createMonthDiv(){
    var div = document.createElement('DIV');
    div.className='monthYearPicker';
    div.id = 'monthPicker';

    for(var no=0;no<monthArray.length;no++){
        var subDiv = document.createElement('DIV');
        subDiv.innerHTML = monthArray[no];
        subDiv.onmouseover = highlightMonthYear;
        subDiv.onmouseout = highlightMonthYear;
        subDiv.onclick = selectMonth;
        subDiv.id = 'monthDiv_' + no;
        subDiv.style.width = '56px';
        subDiv.onselectstart = cancelCalendarEvent;
        div.appendChild(subDiv);
        if(currentMonth && currentMonth==no){
            subDiv.style.color = selectBoxHighlightColor;
            activeSelectBoxMonth = subDiv;
        }

    }
    return div;

}

function changeSelectBoxYear(e,inputObj)
{
    if(!inputObj)inputObj =this;
    var yearItems = inputObj.parentNode.getElementsByTagName('DIV');
    if(inputObj.innerHTML.indexOf('-')>=0){
        var startYear = yearItems[1].innerHTML/1 -1;
        if(activeSelectBoxYear){
            activeSelectBoxYear.style.color='';
        }
    }else{
        var startYear = yearItems[1].innerHTML/1 +1;
        if(activeSelectBoxYear){
            activeSelectBoxYear.style.color='';

        }
    }

    for(var no=1;no<yearItems.length-1;no++){
        yearItems[no].innerHTML = startYear+no-1;
        yearItems[no].id = 'yearDiv' + (startYear/1+no/1-1);

    }
    if(activeSelectBoxYear){
        activeSelectBoxYear.style.color='';
        if(document.getElementById('yearDiv'+currentYear)){
            activeSelectBoxYear = document.getElementById('yearDiv'+currentYear);
            activeSelectBoxYear.style.color=selectBoxHighlightColor;;
        }
    }
}
function changeSelectBoxHour(e,inputObj)
{
    if(!inputObj)inputObj = this;

    var hourItems = inputObj.parentNode.getElementsByTagName('DIV');
    if(inputObj.innerHTML.indexOf('-')>=0){
        var startHour = hourItems[1].innerHTML/1 -1;
        if(startHour<0)startHour=0;
        if(activeSelectBoxHour){
            activeSelectBoxHour.style.color='';
        }
    }else{
        var startHour = hourItems[1].innerHTML/1 +1;
        if(startHour>14)startHour = 14;
        if(activeSelectBoxHour){
            activeSelectBoxHour.style.color='';

        }
    }
    var prefix = '';
    for(var no=1;no<hourItems.length-1;no++){
        if((startHour/1 + no/1) < 11)prefix = '0'; else prefix = '';
        hourItems[no].innerHTML = prefix + (startHour+no-1);

        hourItems[no].id = 'hourDiv' + (startHour/1+no/1-1);

    }
    if(activeSelectBoxHour){
        activeSelectBoxHour.style.color='';
        if(document.getElementById('hourDiv'+currentHour)){
            activeSelectBoxHour = document.getElementById('hourDiv'+currentHour);
            activeSelectBoxHour.style.color=selectBoxHighlightColor;;
        }
    }
}

function updateYearDiv()
{
    var yearSpan = 5;
    if (turnOffYearSpan) {
       yearSpan = 0;
    }
    var div = document.getElementById('yearDropDown');
    var yearItems = div.getElementsByTagName('DIV');
    for(var no=1;no<yearItems.length-1;no++){
        yearItems[no].innerHTML = currentYear/1 -yearSpan + no;
        if(currentYear==(currentYear/1 -yearSpan + no)){
            yearItems[no].style.color = selectBoxHighlightColor;
            activeSelectBoxYear = yearItems[no];
        }else{
            yearItems[no].style.color = '';
        }
    }
}

function updateMonthDiv()
{
    for(no=0;no<12;no++){
        document.getElementById('monthDiv_' + no).style.color = '';
    }
    document.getElementById('monthDiv_' + currentMonth).style.color = selectBoxHighlightColor;
    activeSelectBoxMonth =     document.getElementById('monthDiv_' + currentMonth);
}


function updateHourDiv()
{
    var div = document.getElementById('hourDropDown');
    var hourItems = div.getElementsByTagName('DIV');

    var addHours = 0;
    if((currentHour/1 -6 + 1)<0){
        addHours =     (currentHour/1 -6 + 1)*-1;
    }
    for(var no=1;no<hourItems.length-1;no++){
        var prefix='';
        if((currentHour/1 -6 + no + addHours) < 10)prefix='0';
        hourItems[no].innerHTML = prefix +  (currentHour/1 -6 + no + addHours);
        if(currentHour==(currentHour/1 -6 + no)){
            hourItems[no].style.color = selectBoxHighlightColor;
            activeSelectBoxHour = hourItems[no];
        }else{
            hourItems[no].style.color = '';
        }
    }
}

function updateMinuteDiv()
{
    for(no=0;no<60;no+=intervalSelectBox_minutes){
        var prefix = '';
        if(no<10)prefix = '0';

        document.getElementById('minuteDiv_' + prefix + no).style.color = '';
    }
    if(document.getElementById('minuteDiv_' + currentMinute)){
        document.getElementById('minuteDiv_' + currentMinute).style.color = selectBoxHighlightColor;
        activeSelectBoxMinute = document.getElementById('minuteDiv_' + currentMinute);
    }
}



function createYearDiv()
{

    if(!document.getElementById('yearDropDown')){
        var div = document.createElement('DIV');
        div.className='monthYearPicker';
    }else{
        var div = document.getElementById('yearDropDown');
        var subDivs = div.getElementsByTagName('DIV');
        for(var no=0;no<subDivs.length;no++){
            subDivs[no].parentNode.removeChild(subDivs[no]);
        }
    }


    var d = new Date();
    if(currentYear){
        d.setFullYear(currentYear);
    }

    var startYear = d.getFullYear()/1 - 5;

    var yearSpan = 10;
    if (! turnOffYearSpan) {
        var subDiv = document.createElement('DIV');
        subDiv.innerHTML = '&nbsp;&nbsp;- ';
        subDiv.onclick = changeSelectBoxYear;
        subDiv.onmouseover = highlightMonthYear;
        subDiv.onmouseout = function(){ selectBoxMovementInProgress = false;};
        subDiv.onselectstart = cancelCalendarEvent;
        div.appendChild(subDiv);
    } else {
       startYear = d.getFullYear()/1 - 0;
       yearSpan = 2;
    }

    for(var no=startYear;no<(startYear+yearSpan);no++){
        var subDiv = document.createElement('DIV');
        subDiv.innerHTML = no;
        subDiv.onmouseover = highlightMonthYear;
        subDiv.onmouseout = highlightMonthYear;
        subDiv.onclick = selectYear;
        subDiv.id = 'yearDiv' + no;
        subDiv.onselectstart = cancelCalendarEvent;
        div.appendChild(subDiv);
        if(currentYear && currentYear==no){
            subDiv.style.color = selectBoxHighlightColor;
            activeSelectBoxYear = subDiv;
        }
    }
    if (! turnOffYearSpan) {
        var subDiv = document.createElement('DIV');
        subDiv.innerHTML = '&nbsp;&nbsp;+ ';
        subDiv.onclick = changeSelectBoxYear;
        subDiv.onmouseover = highlightMonthYear;
        subDiv.onmouseout = function(){ selectBoxMovementInProgress = false;};
        subDiv.onselectstart = cancelCalendarEvent;
        div.appendChild(subDiv);
    }
    return div;
}

/* This function creates the hour div at the bottom bar */

function slideCalendarSelectBox()
{
    if(selectBoxMovementInProgress){
        if(activeSelectBox.parentNode.id=='hourDropDown'){
            changeSelectBoxHour(false,activeSelectBox);
        }
        if(activeSelectBox.parentNode.id=='yearDropDown'){
            changeSelectBoxYear(false,activeSelectBox);
        }

    }
    setTimeout('slideCalendarSelectBox()',speedOfSelectBoxSliding);

}

function createHourDiv()
{
    if(!document.getElementById('hourDropDown')){
        var div = document.createElement('DIV');
        div.className='monthYearPicker';
    }else{
        var div = document.getElementById('hourDropDown');
        var subDivs = div.getElementsByTagName('DIV');
        for(var no=0;no<subDivs.length;no++){
            subDivs[no].parentNode.removeChild(subDivs[no]);
        }
    }

    if(!currentHour)currentHour=0;
    var startHour = currentHour/1;
    if(startHour>14)startHour=14;

    var subDiv = document.createElement('DIV');
    subDiv.innerHTML = '&nbsp;&nbsp;- ';
    subDiv.onclick = changeSelectBoxHour;
    subDiv.onmouseover = highlightMonthYear;
    subDiv.onmouseout = function(){ selectBoxMovementInProgress = false;};
    subDiv.onselectstart = cancelCalendarEvent;
    div.appendChild(subDiv);

    for(var no=startHour;no<startHour+10;no++){
        var prefix = '';
        if(no/1<10)prefix='0';
        var subDiv = document.createElement('DIV');
        subDiv.innerHTML = prefix + no;
        subDiv.onmouseover = highlightMonthYear;
        subDiv.onmouseout = highlightMonthYear;
        subDiv.onclick = selectHour;
        subDiv.id = 'hourDiv' + no;
        subDiv.onselectstart = cancelCalendarEvent;
        div.appendChild(subDiv);
        if(currentYear && currentYear==no){
            subDiv.style.color = selectBoxHighlightColor;
            activeSelectBoxYear = subDiv;
        }
    }
    var subDiv = document.createElement('DIV');
    subDiv.innerHTML = '&nbsp;&nbsp;+ ';
    subDiv.onclick = changeSelectBoxHour;
    subDiv.onmouseover = highlightMonthYear;
    subDiv.onmouseout = function(){ selectBoxMovementInProgress = false;};
    subDiv.onselectstart = cancelCalendarEvent;
    div.appendChild(subDiv);

    return div;
}
/* This function creates the minute div at the bottom bar */

function createMinuteDiv()
{
    if(!document.getElementById('minuteDropDown')){
        var div = document.createElement('DIV');
        div.className='monthYearPicker';
    }else{
        var div = document.getElementById('minuteDropDown');
        var subDivs = div.getElementsByTagName('DIV');
        for(var no=0;no<subDivs.length;no++){
            subDivs[no].parentNode.removeChild(subDivs[no]);
        }
    }
    var startMinute = 0;
    var prefix = '';
    for(var no=startMinute;no<60;no+=intervalSelectBox_minutes){

        if(no<10)prefix='0'; else prefix = '';
        var subDiv = document.createElement('DIV');
        subDiv.innerHTML = prefix + no;
        subDiv.onmouseover = highlightMonthYear;
        subDiv.onmouseout = highlightMonthYear;
        subDiv.onclick = selectMinute;
        subDiv.id = 'minuteDiv_' + prefix +  no;
        subDiv.onselectstart = cancelCalendarEvent;
        div.appendChild(subDiv);
        if(currentYear && currentYear==no){
            subDiv.style.color = selectBoxHighlightColor;
            activeSelectBoxYear = subDiv;
        }
    }
    return div;
}

function highlightSelect()
{

    if(this.className=='selectBoxTime'){
        this.className = 'selectBoxTimeOver';
        this.getElementsByTagName('IMG')[0].src = pathToImages + 'down_time_over.gif';
    }else if(this.className=='selectBoxTimeOver'){
        this.className = 'selectBoxTime';
        this.getElementsByTagName('IMG')[0].src = pathToImages + 'down_time.gif';
    }

    if(this.className=='selectBox'){
        this.className = 'selectBoxOver';
        this.getElementsByTagName('IMG')[0].src = pathToImages + 'down_over.gif';
    }else if(this.className=='selectBoxOver'){
        this.className = 'selectBox';
        this.getElementsByTagName('IMG')[0].src = pathToImages + 'down.gif';
    }

}

function highlightArrow()
{
    if(this.src.indexOf('over')>=0){
        if(this.src.indexOf('left')>=0)this.src = pathToImages + 'left.gif';
        if(this.src.indexOf('right')>=0)this.src = pathToImages + 'right.gif';
    }else{
        if(this.src.indexOf('left')>=0)this.src = pathToImages + 'left_over.gif';
        if(this.src.indexOf('right')>=0)this.src = pathToImages + 'right_over.gif';
    }
}

function highlightClose()
{
    if(this.src.indexOf('over')>=0){
        this.src = pathToImages + 'close.gif';
    }else{
        this.src = pathToImages + 'close_over.gif';
    }

}

function closeCalendar(){

    document.getElementById('yearDropDown').style.display='none';
    document.getElementById('monthDropDown').style.display='none';
    document.getElementById('hourDropDown').style.display='none';
    document.getElementById('minuteDropDown').style.display='none';

    calendarDiv.style.display='none';
    if(iframeObj){
        iframeObj.style.display='none';
         //// //// fix for EI frame problem on time dropdowns 09/30/2006
            EIS_Hide_Frame();}
    if(activeSelectBoxMonth)activeSelectBoxMonth.className='';
    if(activeSelectBoxYear)activeSelectBoxYear.className='';

    if (functionToCall != '') {
        eval(functionToCall);
    }
}

function writeTopBar()
{

    var topBar = document.createElement('DIV');
    topBar.className = 'topBar';
    topBar.id = 'topBar';
    calendarDiv.appendChild(topBar);

    // Left arrow
    var leftDiv = document.createElement('DIV');
    leftDiv.style.marginRight = '1px';
    var img = document.createElement('IMG');
    img.src = pathToImages + 'left.gif';
    img.onmouseover = highlightArrow;
    img.onclick = switchMonth;
    img.onmouseout = highlightArrow;
    leftDiv.appendChild(img);
    topBar.appendChild(leftDiv);
    if(Opera)leftDiv.style.width = '16px';

    // Right arrow
    var rightDiv = document.createElement('DIV');
    rightDiv.style.marginRight = '1px';
    var img = document.createElement('IMG');
    img.src = pathToImages + 'right.gif';
    img.onclick = switchMonth;
    img.onmouseover = highlightArrow;
    img.onmouseout = highlightArrow;
    rightDiv.appendChild(img);
    if(Opera)rightDiv.style.width = '16px';
    topBar.appendChild(rightDiv);


    // Month selector
    var monthDiv = document.createElement('DIV');
    monthDiv.id = 'monthSelect';
    monthDiv.onmouseover = highlightSelect;
    monthDiv.onmouseout = highlightSelect;
    monthDiv.onclick = showMonthDropDown;
    var span = document.createElement('SPAN');
    span.innerHTML = monthArray[currentMonth];
    span.id = 'calendar_month_txt';
    monthDiv.appendChild(span);

    var img = document.createElement('IMG');
    img.src = pathToImages + 'down.gif';
    img.style.position = 'absolute';
    img.style.right = '0px';
    monthDiv.appendChild(img);
    monthDiv.className = 'selectBox';
    if(Opera){
        img.style.cssText = 'float:right;position:relative';
        img.style.position = 'relative';
        img.style.styleFloat = 'right';
    }
    topBar.appendChild(monthDiv);

    var monthPicker = createMonthDiv();
    monthPicker.style.left = '37px';
    monthPicker.style.top = monthDiv.offsetTop + monthDiv.offsetHeight + 1 + 'px';
    monthPicker.style.width ='60px';
    monthPicker.id = 'monthDropDown';

    calendarDiv.appendChild(monthPicker);

    // Year selector
    var yearDiv = document.createElement('DIV');
    yearDiv.onmouseover = highlightSelect;
    yearDiv.onmouseout = highlightSelect;
    yearDiv.onclick = showYearDropDown;
    var span = document.createElement('SPAN');
    span.innerHTML = currentYear;
    span.id = 'calendar_year_txt';
    yearDiv.appendChild(span);
    topBar.appendChild(yearDiv);

    var img = document.createElement('IMG');
    img.src = pathToImages + 'down.gif';
    yearDiv.appendChild(img);
    yearDiv.className = 'selectBox';

    if(Opera){
        yearDiv.style.width = '50px';
        img.style.cssText = 'float:right';
        img.style.position = 'relative';
        img.style.styleFloat = 'right';
    }

    var yearPicker = createYearDiv();
    yearPicker.style.left = '113px';
    yearPicker.style.top = monthDiv.offsetTop + monthDiv.offsetHeight + 1 + 'px';
    yearPicker.style.width = '35px';
    yearPicker.id = 'yearDropDown';
    calendarDiv.appendChild(yearPicker);


    var img = document.createElement('IMG');
    img.src = pathToImages + 'close.gif';
    img.style.styleFloat = 'right';
    img.onmouseover = highlightClose;
    img.onmouseout = highlightClose;
    img.onclick = closeCalendar;
    topBar.appendChild(img);
    if(!document.all){
        img.style.position = 'absolute';
        img.style.right = '2px';
    }



}

function writeCalendarContent()
{
    var calendarContentDivExists = true;
    if(!calendarContentDiv){
        calendarContentDiv = document.createElement('DIV');
        calendarDiv.appendChild(calendarContentDiv);
        calendarContentDivExists = false;
    }
    currentMonth = currentMonth/1;
    var d = new Date();

    d.setFullYear(currentYear);
    d.setDate(1);
    d.setMonth(currentMonth);

    var dayStartOfMonth = d.getDay();
    if (! weekStartsOnSunday) {
      if(dayStartOfMonth==0)dayStartOfMonth=7;
      dayStartOfMonth--;
   }

    document.getElementById('calendar_year_txt').innerHTML = currentYear;
    document.getElementById('calendar_month_txt').innerHTML = monthArray[currentMonth];
    document.getElementById('calendar_hour_txt').innerHTML = currentHour;
    document.getElementById('calendar_minute_txt').innerHTML = currentMinute;

    var existingTable = calendarContentDiv.getElementsByTagName('TABLE');
    if(existingTable.length>0){
        calendarContentDiv.removeChild(existingTable[0]);
    }

    var calTable = document.createElement('TABLE');
    calTable.width = '100%';
    calTable.cellSpacing = '0';
    calendarContentDiv.appendChild(calTable);




    var calTBody = document.createElement('TBODY');
    calTable.appendChild(calTBody);
    var row = calTBody.insertRow(-1);
    row.className = 'calendar_week_row';
   if (showWeekNumber) {
      var cell = row.insertCell(-1);
       cell.innerHTML = weekString;
       cell.className = 'calendar_week_column';
       cell.style.backgroundColor = selectBoxRolloverBgColor;
    }

    for(var no=0;no<dayArray.length;no++){
        var cell = row.insertCell(-1);
        cell.innerHTML = dayArray[no];
    }

    var row = calTBody.insertRow(-1);

   if (showWeekNumber) {
       var cell = row.insertCell(-1);
       cell.className = 'calendar_week_column';
       cell.style.backgroundColor = selectBoxRolloverBgColor;
       var week = getWeek(currentYear,currentMonth,1);
       cell.innerHTML = week;        // Week
    }
    for(var no=0;no<dayStartOfMonth;no++){
        var cell = row.insertCell(-1);
        cell.innerHTML = '&nbsp;';
    }

    var colCounter = dayStartOfMonth;
    var daysInMonth = daysInMonthArray[currentMonth];
    if(daysInMonth==28){
        if(isLeapYear(currentYear))daysInMonth=29;
    }

    for(var no=1;no<=daysInMonth;no++){
        d.setDate(no-1);
        if(colCounter>0 && colCounter%7==0){
            var row = calTBody.insertRow(-1);
         if (showWeekNumber) {
            var cell = row.insertCell(-1);
            cell.className = 'calendar_week_column';
            var week = getWeek(currentYear,currentMonth,no);
            cell.innerHTML = week;        // Week
            cell.style.backgroundColor = selectBoxRolloverBgColor;
         }
        }
        var cell = row.insertCell(-1);
        if(currentYear==inputYear && currentMonth == inputMonth && no==inputDay){
            cell.className='activeDay';
        }
        cell.innerHTML = no;
        cell.onclick = pickDate;
        colCounter++;
    }


    if(!document.all){
        if(calendarContentDiv.offsetHeight)
            document.getElementById('topBar').style.top = calendarContentDiv.offsetHeight + document.getElementById('timeBar').offsetHeight + document.getElementById('topBar').offsetHeight -1 + 'px';
        else{
            document.getElementById('topBar').style.top = '';
            document.getElementById('topBar').style.bottom = '0px';
        }

    }

    if(iframeObj){
        if(!calendarContentDivExists)setTimeout('resizeIframe()',350);else setTimeout('resizeIframe()',10);
    }




}

function resizeIframe()
{
    iframeObj.style.width = calendarDiv.offsetWidth + 'px';
    iframeObj.style.height = calendarDiv.offsetHeight + 'px' ;


}

function pickTodaysDate()
{
    var d = new Date();
    currentMonth = d.getMonth();
    currentYear = d.getFullYear();
    pickDate(false,d.getDate());

}

function pickDate(e,inputDay)
{
    var month = currentMonth/1 +1;
    if(month<10)month = '0' + month;
    var day;
    if(!inputDay && this)day = this.innerHTML; else day = inputDay;

    if(day/1<10)day = '0' + day;
    if(returnFormat){
        returnFormat = returnFormat.replace('dd',day);
        returnFormat = returnFormat.replace('mm',month);
        returnFormat = returnFormat.replace('yyyy',currentYear);
        returnFormat = returnFormat.replace('hh',currentHour);
        returnFormat = returnFormat.replace('ii',currentMinute);
        returnFormat = returnFormat.replace('d',day/1);
        returnFormat = returnFormat.replace('m',month/1);

        returnDateTo.value = returnFormat;
        try{
            returnDateTo.onchange();
        }catch(e){

        }
    }else{
        for(var no=0;no<returnDateToYear.options.length;no++){
            if(returnDateToYear.options[no].value==currentYear){
                returnDateToYear.selectedIndex=no;
                break;
            }
        }
        for(var no=0;no<returnDateToMonth.options.length;no++){
            if(returnDateToMonth.options[no].value==parseInt(month)){
                returnDateToMonth.selectedIndex=no;
                break;
            }
        }
        for(var no=0;no<returnDateToDay.options.length;no++){
            if(returnDateToDay.options[no].value==parseInt(day)){
                returnDateToDay.selectedIndex=no;
                break;
            }
        }
        if(calendarDisplayTime){
            for(var no=0;no<returnDateToHour.options.length;no++){
                if(returnDateToHour.options[no].value==parseInt(currentHour)){
                    returnDateToHour.selectedIndex=no;
                    break;
                }
            }
            for(var no=0;no<returnDateToMinute.options.length;no++){
                if(returnDateToMinute.options[no].value==parseInt(currentMinute)){
                    returnDateToMinute.selectedIndex=no;
                    break;
                }
            }
        }
    }
    closeCalendar();

}

// This function is from http://www.codeproject.com/csharp/gregorianwknum.asp
// Only changed the month add
function getWeek(year,month,day){
   if (! weekStartsOnSunday) {
       day = (day/1);
    } else {
       day = (day/1)+1;
    }
    year = year /1;
    month = month/1 + 1; //use 1-12
    var a = Math.floor((14-(month))/12);
    var y = year+4800-a;
    var m = (month)+(12*a)-3;
    var jd = day + Math.floor(((153*m)+2)/5) +
                 (365*y) + Math.floor(y/4) - Math.floor(y/100) +
                 Math.floor(y/400) - 32045;      // (gregorian calendar)
    var d4 = (jd+31741-(jd%7))%146097%36524%1461;
    var L = Math.floor(d4/1460);
    var d1 = ((d4-L)%365)+L;
    NumberOfWeek = Math.floor(d1/7) + 1;
    return NumberOfWeek;
}

function writeTimeBar()
{
    var timeBar = document.createElement('DIV');
    timeBar.id = 'timeBar';
    timeBar.className = 'timeBar';

    var subDiv = document.createElement('DIV');
    subDiv.innerHTML = 'Time:';
    //timeBar.appendChild(subDiv);

    // Year selector
    var hourDiv = document.createElement('DIV');
    hourDiv.onmouseover = highlightSelect;
    hourDiv.onmouseout = highlightSelect;
    hourDiv.onclick = showHourDropDown;
    hourDiv.style.width = '30px';
    var span = document.createElement('SPAN');
    span.innerHTML = currentHour;
    span.id = 'calendar_hour_txt';
    hourDiv.appendChild(span);
    timeBar.appendChild(hourDiv);

    var img = document.createElement('IMG');
    img.src = pathToImages + 'down_time.gif';
    hourDiv.appendChild(img);
    hourDiv.className = 'selectBoxTime';

    if(Opera){
        hourDiv.style.width = '30px';
        img.style.cssText = 'float:right';
        img.style.position = 'relative';
        img.style.styleFloat = 'right';
    }

    var hourPicker = createHourDiv();
    hourPicker.style.left = '130px';
    //hourPicker.style.top = monthDiv.offsetTop + monthDiv.offsetHeight + 1 + 'px';
    hourPicker.style.width = '35px';
    hourPicker.id = 'hourDropDown';
    calendarDiv.appendChild(hourPicker);

    // Add Minute picker

    // Year selector
    var minuteDiv = document.createElement('DIV');
    minuteDiv.onmouseover = highlightSelect;
    minuteDiv.onmouseout = highlightSelect;
    minuteDiv.onclick = showMinuteDropDown;
    minuteDiv.style.width = '30px';
    var span = document.createElement('SPAN');
    span.innerHTML = currentMinute;

    span.id = 'calendar_minute_txt';
    minuteDiv.appendChild(span);
    timeBar.appendChild(minuteDiv);

    var img = document.createElement('IMG');
    img.src = pathToImages + 'down_time.gif';
    minuteDiv.appendChild(img);
    minuteDiv.className = 'selectBoxTime';

    if(Opera){
        minuteDiv.style.width = '30px';
        img.style.cssText = 'float:right';
        img.style.position = 'relative';
        img.style.styleFloat = 'right';
    }

    var minutePicker = createMinuteDiv();
    minutePicker.style.left = '167px';
    //minutePicker.style.top = monthDiv.offsetTop + monthDiv.offsetHeight + 1 + 'px';
    minutePicker.style.width = '35px';
    minutePicker.id = 'minuteDropDown';
    calendarDiv.appendChild(minutePicker);


    return timeBar;

}

function writeBottomBar()
{
    var d = new Date();
    var bottomBar = document.createElement('DIV');

    bottomBar.id = 'bottomBar';

    bottomBar.style.cursor = 'pointer';
    bottomBar.className = 'todaysDate';
    // var todayStringFormat = '[todayString] [dayString] [day] [monthString] [year]';    ;;

    var subDiv = document.createElement('DIV');
    subDiv.onclick = pickTodaysDate;
    subDiv.id = 'todaysDateString';
    subDiv.style.width = (calendarDiv.offsetWidth - 95) + 'px';
    var day = d.getDay();
    if (! weekStartsOnSunday) {
      if(day==0)day = 7;
      day--;
   }

    var bottomString = todayStringFormat;
    bottomString = bottomString.replace('[monthString]',monthArrayShort[d.getMonth()]);
    bottomString = bottomString.replace('[day]',d.getDate());
    bottomString = bottomString.replace('[year]',d.getFullYear());
    bottomString = bottomString.replace('[dayString]',dayArray[day].toLowerCase());
    bottomString = bottomString.replace('[UCFdayString]',dayArray[day]);
    bottomString = bottomString.replace('[todayString]',todayString);


    subDiv.innerHTML = todayString + ': ' + d.getDate() + '. ' + monthArrayShort[d.getMonth()] + ', ' +  d.getFullYear() ;
    subDiv.innerHTML = bottomString ;
    bottomBar.appendChild(subDiv);

    var timeDiv = writeTimeBar();
    bottomBar.appendChild(timeDiv);

    calendarDiv.appendChild(bottomBar);



}
function getTopPos(inputObj)
{

  var returnValue = inputObj.offsetTop + inputObj.offsetHeight;
  while((inputObj = inputObj.offsetParent) != null)returnValue += inputObj.offsetTop;
  return returnValue + calendar_offsetTop;
}

function getleftPos(inputObj)
{
  var returnValue = inputObj.offsetLeft;
  while((inputObj = inputObj.offsetParent) != null)returnValue += inputObj.offsetLeft;
  return returnValue + calendar_offsetLeft;
}

function positionCalendar(inputObj)
{
    calendarDiv.style.left = getleftPos(inputObj) + 'px';
    calendarDiv.style.top = getTopPos(inputObj) + 'px';
    if(iframeObj){
        iframeObj.style.left = calendarDiv.style.left;
        iframeObj.style.top =  calendarDiv.style.top;
        //// fix for EI frame problem on time dropdowns 09/30/2006
        iframeObj2.style.left = calendarDiv.style.left;
        iframeObj2.style.top =  calendarDiv.style.top;
    }

}

function initCalendar()
{
    if(MSIE){
        iframeObj = document.createElement('IFRAME');
        iframeObj.style.filter = 'alpha(opacity=0)';
        iframeObj.style.position = 'absolute';
        iframeObj.border='0px';
        iframeObj.style.border = '0px';
        iframeObj.style.backgroundColor = '#FF0000';
        //// fix for EI frame problem on time dropdowns 09/30/2006
        iframeObj2 = document.createElement('IFRAME');
        iframeObj2.style.position = 'absolute';
        iframeObj2.border='0px';
        iframeObj2.style.border = '0px';
        iframeObj2.style.height = '1px';
        iframeObj2.style.width = '1px';
        //// fix for EI frame problem on time dropdowns 09/30/2006
        // Added fixed for HTTPS
        iframeObj2.src = 'blank.html';
        iframeObj.src = 'blank.html';
        document.body.appendChild(iframeObj2);  // gfb move this down AFTER the .src is set
        document.body.appendChild(iframeObj);
    }

    calendarDiv = document.createElement('DIV');
    calendarDiv.id = 'calendarDiv';
    calendarDiv.style.zIndex = 100001;
    slideCalendarSelectBox();

    document.body.appendChild(calendarDiv);
    writeBottomBar();
    writeTopBar();



    if(!currentYear){
        var d = new Date();
        currentMonth = d.getMonth();
        currentYear = d.getFullYear();
    }
    writeCalendarContent();



}

function setTimeProperties()
{
    if(!calendarDisplayTime){
        document.getElementById('timeBar').style.display='none';
        document.getElementById('timeBar').style.visibility='hidden';
        document.getElementById('todaysDateString').style.width = '100%';


    }else{
        document.getElementById('timeBar').style.display='block';
        document.getElementById('timeBar').style.visibility='visible';
        document.getElementById('hourDropDown').style.top = document.getElementById('calendar_minute_txt').parentNode.offsetHeight + calendarContentDiv.offsetHeight + document.getElementById('topBar').offsetHeight + 'px';
        document.getElementById('minuteDropDown').style.top = document.getElementById('calendar_minute_txt').parentNode.offsetHeight + calendarContentDiv.offsetHeight + document.getElementById('topBar').offsetHeight + 'px';
        document.getElementById('minuteDropDown').style.right = '50px';
        document.getElementById('hourDropDown').style.right = '50px';
        document.getElementById('todaysDateString').style.width = '115px';
    }
}

function calendarSortItems(a,b)
{
    return a/1 - b/1;
}


function displayCalendar(inputField,format,buttonObj,displayTime,timeInput,f)
{
    functionToCall = f; 
    if(displayTime)calendarDisplayTime=true; else calendarDisplayTime = false;
    
    if(inputField.value.length>6){ //dates must have at least 6 digits...
       if(!inputField.value.match(/^[0-9]*?$/gi)){
             var items = inputField.value.split(/[^0-9]/gi);
            var positionArray = new Array();
            positionArray['m'] = format.indexOf('mm');
            if(positionArray['m']==-1)positionArray['m'] = format.indexOf('m');
            positionArray['d'] = format.indexOf('dd');
            if(positionArray['d']==-1)positionArray['d'] = format.indexOf('d');
            positionArray['y'] = format.indexOf('yyyy');
            positionArray['h'] = format.indexOf('hh');
            positionArray['i'] = format.indexOf('ii');

            var positionArrayNumeric = Array();
            positionArrayNumeric[0] = positionArray['m'];
            positionArrayNumeric[1] = positionArray['d'];
            positionArrayNumeric[2] = positionArray['y'];
            positionArrayNumeric[3] = positionArray['h'];
            positionArrayNumeric[4] = positionArray['i'];


            positionArrayNumeric = positionArrayNumeric.sort(calendarSortItems);
            var itemIndex = -1;
            currentHour = '00';
            currentMinute = '00';
            for(var no=0;no<positionArrayNumeric.length;no++){
                if(positionArrayNumeric[no]==-1)continue;
                itemIndex++;
                if(positionArrayNumeric[no]==positionArray['m']){
                    currentMonth = items[itemIndex]-1;
                    continue;
                }
                if(positionArrayNumeric[no]==positionArray['y']){
                    currentYear = items[itemIndex];
                    continue;
                }
                if(positionArrayNumeric[no]==positionArray['d']){
                    tmpDay = items[itemIndex];
                    continue;
                }
                if(positionArrayNumeric[no]==positionArray['h']){
                    currentHour = items[itemIndex];
                    continue;
                }
                if(positionArrayNumeric[no]==positionArray['i']){
                    currentMinute = items[itemIndex];
                    continue;
                }
            }

            currentMonth = currentMonth / 1;
            tmpDay = tmpDay / 1;
        }else{
            var monthPos = format.indexOf('mm');
            currentMonth = inputField.value.substr(monthPos,2)/1 -1;
            var yearPos = format.indexOf('yyyy');
            currentYear = inputField.value.substr(yearPos,4);
            var dayPos = format.indexOf('dd');
            tmpDay = inputField.value.substr(dayPos,2);

            var hourPos = format.indexOf('hh');
            if(hourPos>=0){
                tmpHour = inputField.value.substr(hourPos,2);
                currentHour = tmpHour;
            }else{
                currentHour = '00';
            }
            var minutePos = format.indexOf('ii');
            if(minutePos>=0){
                tmpMinute = inputField.value.substr(minutePos,2);
                currentMinute = tmpMinute;
            }else{
                currentMinute = '00';
            }
        }
    }else{
        var d = new Date();
        currentMonth = d.getMonth();
        currentYear = d.getFullYear();
        currentHour = '08';
        currentMinute = '00';
        tmpDay = d.getDate();
    }

    inputYear = currentYear;
    inputMonth = currentMonth;
    inputDay = tmpDay/1;


    if(!calendarDiv){
        initCalendar();
    }else{
        if(calendarDiv.style.display=='block'){
            closeCalendar();
            return false;
        }
        writeCalendarContent();
    }



    returnFormat = format;
    returnDateTo = inputField;
    positionCalendar(buttonObj);
    calendarDiv.style.visibility = 'visible';
    calendarDiv.style.display = 'block';
    if(iframeObj){
        iframeObj.style.display = '';
        iframeObj.style.height = '140px';
        iframeObj.style.width = '195px';
                iframeObj2.style.display = '';
        iframeObj2.style.height = '140px';
        iframeObj2.style.width = '195px';
    }

    setTimeProperties();
    updateYearDiv();
    updateMonthDiv();
    updateMinuteDiv();
    updateHourDiv();

}

function displayCalendarSelectBox(yearInput,monthInput,dayInput,hourInput,minuteInput,buttonObj)
{
    if(!hourInput)calendarDisplayTime=false; else calendarDisplayTime = true;

    currentMonth = monthInput.options[monthInput.selectedIndex].value/1-1;
    currentYear = yearInput.options[yearInput.selectedIndex].value;
    if(hourInput){
        currentHour = hourInput.options[hourInput.selectedIndex].value;
        inputHour = currentHour/1;
    }
    if(minuteInput){
        currentMinute = minuteInput.options[minuteInput.selectedIndex].value;
        inputMinute = currentMinute/1;
    }

    inputYear = yearInput.options[yearInput.selectedIndex].value;
    inputMonth = monthInput.options[monthInput.selectedIndex].value/1 - 1;
    inputDay = dayInput.options[dayInput.selectedIndex].value/1;

    if(!calendarDiv){
        initCalendar();
    }else{
        writeCalendarContent();
    }



    returnDateToYear = yearInput;
    returnDateToMonth = monthInput;
    returnDateToDay = dayInput;
    returnDateToHour = hourInput;
    returnDateToMinute = minuteInput;




    returnFormat = false;
    returnDateTo = false;
    positionCalendar(buttonObj);
    calendarDiv.style.visibility = 'visible';
    calendarDiv.style.display = 'block';
    if(iframeObj){
        iframeObj.style.display = '';
        iframeObj.style.height = calendarDiv.offsetHeight + 'px';
        iframeObj.style.width = calendarDiv.offsetWidth + 'px';
        //// fix for EI frame problem on time dropdowns 09/30/2006
        iframeObj2.style.display = '';
        iframeObj2.style.height = calendarDiv.offsetHeight + 'px';
        iframeObj2.style.width = calendarDiv.offsetWidth + 'px'
    }
    setTimeProperties();
    updateYearDiv();
    updateMonthDiv();
    updateHourDiv();
    updateMinuteDiv();

}

/*******************************************************************/
/*																   */
/*							IE HOVER FIX						   */
/*																   */
/*******************************************************************/

/** JavaScript **/
ieHover = function() {
  var parent = document.getElementById('nav');
  if (parent == null) return;
  var ieULs = parent.getElementsByTagName('ul');
  /** IE script to cover <select> elements with <iframe>s **/
  for (j=0; j<ieULs.length; j++) {
    ieULs[j].innerHTML = ('<iframe src="about:blank" scrolling="no" frameborder="0"></iframe>' + ieULs[j].innerHTML);
    var ieMat = ieULs[j].firstChild;
		ieMat.style.width=ieULs[j].offsetWidth+"px";
		ieMat.style.height=ieULs[j].offsetHeight+"px";	
		ieULs[j].style.zIndex="99";
  }
  /** IE script to change class on mouseover **/
	var ieLIs = parent.getElementsByTagName('li');
	for (var i=0; i<ieLIs.length; i++) if (ieLIs[i]) {
		ieLIs[i].onmouseover=function() {this.className+=" iehover";}
		ieLIs[i].onmouseout=function() {this.className=this.className.replace(' iehover', '');}
	}
}
if (window.attachEvent) window.attachEvent('onload', ieHover);
/** end **/


/*******************************************************************/
/*																   */
/*							CONSOLE								   */
/*																   */
/*******************************************************************/

function render_graph(){
  var ox=40,oy=410;
  var mx=370,my=20;
  var pad=oy-160;
  
  var scolors = new Array('#ff0000', '#00ff00', '#0000ff', '#ffff00', '#00ffff'
                          , '#ff00ff', '#ff9060', '#60ff90', '#9060ff');
  
  var canvas;
  canvas = new jsGraphics('bid_graph');
  
  canvas.setColor('black');
  canvas.drawLine(ox-1, oy, mx, oy);
  canvas.drawLine(ox, oy+1, ox, my);
  canvas.drawPolyLine(new Array(mx-2, mx, mx-2), new Array(oy-2, oy, oy+2));
  canvas.drawPolyLine(new Array(ox-2, ox, ox+2), new Array(my+2, my, my+2));
  
  var graph_data = document.getElementById('graph_data').innerHTML.split(';');
  
  canvas.setFont("arial","9px", Font.PLAIN); 
  canvas.drawString(graph_data[0],2,oy+4,40,"center");  
  canvas.drawString(graph_data[1],mx-40,oy+4,40,"center");
  canvas.drawStringRect(graph_data[2],2,my,ox-4,"center");
  canvas.drawStringRect(graph_data[3],2,pad,ox-4,"center");
  
  
  var supp_bids = document.getElementById('bid_coords').innerHTML.split('|');
//  alert(document.getElementById('bid_coords').innerHTML);
  
  for (i=0;i<supp_bids.length - 1;i++) {    
    if (supp_bids[i].length< 2) continue;
    canvas.setColor(scolors[i]);
    var coords=supp_bids[i].split(';');
    var x = coords[0].split(',');
    var y = coords[1].split(',');
    var details = coords[2].split(',');
    for (var j=0 ; j<x.length-1 ; j++ ) {
      var x1=parseInt(x[j]);
      var y1=parseInt(y[j]);
      var x2=parseInt(x[j+1]);
      var y2=parseInt(y[j+1]);
			canvas.drawLine(x1, y1, x2, y2);
    }
    for (var j=0;j<x.length;j++) {
      canvas.drawTitledDot(x[j]-1, y[j]-1, 4, details[j]);
    }
  }

  canvas.paint();
}

//refreshes the bid list and graph
function refresh_bids(){
  sndReq('b_console_bids.php','','auct_status',f3);
}


/*******************************************************************/
/*																   */
/*							MODAL MESSAGE					   	   */
/*																   */
/*******************************************************************/

/************************************************************************************************************
*	DHTML modal dialog box
*
*	Created:						August, 26th, 2006
*	@class Purpose of class:		Display a modal dialog box on the screen.
*			
*	Css files used by this script:	modal-message.css
*
*	Demos of this class:			demo-modal-message-1.html
*
* 	Update log:
*
************************************************************************************************************/


/**
* @constructor
*/

DHTML_modalMessage = function()
{
	var url;								// url of modal message
	var htmlOfModalMessage;					// html of modal message
	
	var divs_transparentDiv;				// Transparent div covering page content
	var divs_content;						// Modal message div.
	var iframe;								// Iframe used in ie
	var layoutCss;							// Name of css file;
	var width;								// Width of message box
	var height;								// Height of message box
	
	var existingBodyOverFlowStyle;			// Existing body overflow css
	var dynContentObj;						// Reference to dynamic content object
	var cssClassOfMessageBox;				// Alternative css class of message box - in case you want a different appearance on one of them
	var shadowDivVisible;					// Shadow div visible ? 
	var shadowOffset; 						// X and Y offset of shadow(pixels from content box)
	var MSIE;
		
	this.url = '';							// Default url is blank
	this.htmlOfModalMessage = '';			// Default message is blank
	this.layoutCss = 'modal-message.css';	// Default CSS file
//	this.height = 200;						// Default height of modal message
//	this.width = 700;						// Default width of modal message
	this.cssClassOfMessageBox = false;		// Default alternative css class for the message box
	this.shadowDivVisible = true;			// Shadow div is visible by default
	this.shadowOffset = 5;					// Default shadow offset.
	this.MSIE = false;
	if(navigator.userAgent.indexOf('MSIE')>=0) this.MSIE = true;
	

}

DHTML_modalMessage.prototype = {
	// {{{ setSource(urlOfSource)
    /**
     *	Set source of the modal dialog box
     * 	
     *
     * @public	
     */		
	setSource : function(urlOfSource)
	{
		this.url = urlOfSource;
		
	}	
	// }}}	
	,
	// {{{ setHtmlContent(newHtmlContent)
    /**
     *	Setting static HTML content for the modal dialog box.
     * 	
     *	@param String newHtmlContent = Static HTML content of box
     *
     * @public	
     */		
	setHtmlContent : function(newHtmlContent)
	{
		this.htmlOfModalMessage = newHtmlContent;
		
	}
	// }}}		
	,
	// {{{ setSize(width,height)
    /**
     *	Set the size of the modal dialog box
     * 	
     *	@param int width = width of box
     *	@param int height = height of box
     *
     * @public	
     */		
	setSize : function(width,height)
	{
		if(width)this.width = width;
		if(height)this.height = height;		
	}
	// }}}		
	,		
	// {{{ setCssClassMessageBox(newCssClass)
    /**
     *	Assign the message box to a new css class.(in case you wants a different appearance on one of them)
     * 	
     *	@param String newCssClass = Name of new css class (Pass false if you want to change back to default)
     *
     * @public	
     */		
	setCssClassMessageBox : function(newCssClass)
	{
		this.cssClassOfMessageBox = newCssClass;
		if(this.divs_content){
			if(this.cssClassOfMessageBox)
				this.divs_content.className=this.cssClassOfMessageBox;
			else
				this.divs_content.className='modalDialog_contentDiv';	
		}
					
	}
	// }}}		
	,	
	// {{{ setShadowOffset(newShadowOffset)
    /**
     *	Specify the size of shadow
     * 	
     *	@param Int newShadowOffset = Offset of shadow div(in pixels from message box - x and y)
     *
     * @public	
     */		
	setShadowOffset : function(newShadowOffset)
	{
		this.shadowOffset = newShadowOffset
					
	}
	// }}}		
	,	
	// {{{ display()
    /**
     *	Display the modal dialog box
     * 	
     *
     * @public	
     */		
	display : function()
	{
		if(!this.divs_transparentDiv){
			this.__createDivs();
		}	
		
		// Redisplaying divs
		this.divs_transparentDiv.style.display='block';
		this.divs_content.style.display='block';
		this.divs_shadow.style.display='block';		
		if(this.MSIE)this.iframe.style.display='block';	
		this.__resizeDivs();
		
		/* Call the __resizeDivs method twice in case the css file has changed. The first execution of this method may not catch these changes */
		window.refToThisModalBoxObj = this;		
		setTimeout('window.refToThisModalBoxObj.__resizeDivs()',150);
		
		this.__insertContent();	// Calling method which inserts content into the message div.
	}
	// }}}		
	,
	// {{{ ()
    /**
     *	Display the modal dialog box
     * 	
     *
     * @public	
     */		
	setShadowDivVisible : function(visible)
	{
		this.shadowDivVisible = visible;
	}
	// }}}	
	,
	// {{{ close()
    /**
     *	Close the modal dialog box
     * 	
     *
     * @public	
     */		
	close : function()
	{
		//document.documentElement.style.overflow = '';	// Setting the CSS overflow attribute of the <html> tag back to default.
		
		/* Hiding divs */
		this.divs_transparentDiv.style.display='none';
		this.divs_content.style.display='none';
		this.divs_shadow.style.display='none';
		if(this.MSIE)this.iframe.style.display='none';
		
	}	
	// }}}	
	,
	// {{{ __addEvent()
    /**
     *	Add event
     * 	
     *
     * @private	
     */		
	addEvent : function(whichObject,eventType,functionName,suffix)
	{ 
	  if(!suffix)suffix = '';
	  if(whichObject.attachEvent){ 
	    whichObject['e'+eventType+functionName+suffix] = functionName; 
	    whichObject[eventType+functionName+suffix] = function(){whichObject['e'+eventType+functionName+suffix]( window.event );} 
	    whichObject.attachEvent( 'on'+eventType, whichObject[eventType+functionName+suffix] ); 
	  } else 
	    whichObject.addEventListener(eventType,functionName,false); 	    
	} 
	// }}}	
	,
	// {{{ __createDivs()
    /**
     *	Create the divs for the modal dialog box
     * 	
     *
     * @private	
     */		
	__createDivs : function()
	{
		// Creating transparent div
		this.divs_transparentDiv = document.createElement('DIV');
		this.divs_transparentDiv.className='modalDialog_transparentDivs';
		this.divs_transparentDiv.style.left = '0px';
		this.divs_transparentDiv.style.top = '0px';
		
		document.body.appendChild(this.divs_transparentDiv);
		// Creating content div
		this.divs_content = document.createElement('DIV');
		this.divs_content.className = 'modalDialog_contentDiv';
		this.divs_content.id = 'DHTMLSuite_modalBox_contentDiv';
		this.divs_content.style.zIndex = 100000;
		
		if(this.MSIE){
			this.iframe = document.createElement('<IFRAME src="about:blank" frameborder=0>');
			this.iframe.style.zIndex = 90000;
			this.iframe.style.position = 'absolute';
			document.body.appendChild(this.iframe);	
		}
			
		document.body.appendChild(this.divs_content);
		// Creating shadow div
		this.divs_shadow = document.createElement('DIV');
		this.divs_shadow.className = 'modalDialog_contentDiv_shadow';
		this.divs_shadow.style.zIndex = 95000;
		document.body.appendChild(this.divs_shadow);
		window.refToModMessage = this;
		this.addEvent(window,'scroll',function(e){ window.refToModMessage.__repositionTransparentDiv() });
		this.addEvent(window,'resize',function(e){ window.refToModMessage.__repositionTransparentDiv() });
		

	}
	// }}}
	,
	// {{{ __getBrowserSize()
    /**
     *	Get browser size
     * 	
     *
     * @private	
     */		
	__getBrowserSize : function()
	{
    	var bodyWidth = document.documentElement.clientWidth;
    	var bodyHeight = document.documentElement.clientHeight;
    	
		var bodyWidth, bodyHeight; 
		if (self.innerHeight){ // all except Explorer 
		 
		   bodyWidth = self.innerWidth - 17; 
		   bodyHeight = self.innerHeight; 
		}  else if (document.documentElement && document.documentElement.clientHeight) {
		   // Explorer 6 Strict Mode 		 
		   bodyWidth = document.documentElement.clientWidth; 
		   bodyHeight = document.documentElement.clientHeight; 
		} else if (document.body) {// other Explorers 		 
		   bodyWidth = document.body.clientWidth; 
		   bodyHeight = document.body.clientHeight; 
		} 
		return [bodyWidth,bodyHeight];		
		
	}
	// }}}	
	,
	// {{{ __resizeDivs()
    /**
     *	Resize the message divs
     * 	
     *
     * @private	
     */	
    __resizeDivs : function()
    {
    	
    	var topOffset = Math.max(document.body.scrollTop,document.documentElement.scrollTop);

		if(this.cssClassOfMessageBox)
			this.divs_content.className=this.cssClassOfMessageBox;
		else
			this.divs_content.className='modalDialog_contentDiv';	
			    	
    	if(!this.divs_transparentDiv)return;
    	
    	// Preserve scroll position
    	var st = Math.max(document.body.scrollTop,document.documentElement.scrollTop);
    	var sl = Math.max(document.body.scrollLeft,document.documentElement.scrollLeft);
    	
    	window.scrollTo(sl,st);
    	setTimeout('window.scrollTo(' + sl + ',' + st + ');',10);

    	this.__repositionTransparentDiv();
    	

		var brSize = this.__getBrowserSize();
		var bodyWidth = brSize[0];
		var bodyHeight = brSize[1];
    	
    	// Setting width and height of content div
//      	this.divs_content.style.width = this.width + 'px';
//    	this.divs_content.style.height= this.height + 'px';  	
    	
    	// Creating temporary width variables since the actual width of the content div could be larger than this.width and this.height(i.e. padding and border)
    	var tmpWidth = this.divs_content.offsetWidth;	
    	var tmpHeight = this.divs_content.offsetHeight;
    	
    	
    	// Setting width and height of left transparent div

    	this.divs_content.style.left = Math.ceil((bodyWidth - tmpWidth) / 2) + 'px';;
    	this.divs_content.style.top = (Math.ceil((bodyHeight - tmpHeight) / 2) +  topOffset) + 'px';
 		if(this.MSIE){
 			this.iframe.style.left = this.divs_content.style.left;
 			this.iframe.style.top = this.divs_content.style.top;
 			this.iframe.style.width = this.divs_content.offsetWidth;
 			this.iframe.style.height = this.divs_content.offsetHeight;
 		}
 		
    	this.divs_shadow.style.left = (this.divs_content.style.left.replace('px','')/1 + this.shadowOffset) + 'px';
    	this.divs_shadow.style.top = (this.divs_content.style.top.replace('px','')/1 + this.shadowOffset) + 'px';
    	this.divs_shadow.style.height = tmpHeight + 'px';
    	this.divs_shadow.style.width = tmpWidth + 'px';
    	
    	
    	
    	if(!this.shadowDivVisible)this.divs_shadow.style.display='none';	// Hiding shadow if it has been disabled
    	
    	
    }
    // }}}	
    ,
	// {{{ __insertContent()
    /**
     *	Insert content into the content div
     * 	
     *
     * @private	
     */	    
    __repositionTransparentDiv : function()
    {
    	this.divs_transparentDiv.style.top = Math.max(document.body.scrollTop,document.documentElement.scrollTop) + 'px';
    	this.divs_transparentDiv.style.left = Math.max(document.body.scrollLeft,document.documentElement.scrollLeft) + 'px';
		var brSize = this.__getBrowserSize();
		var bodyWidth = brSize[0];
		var bodyHeight = brSize[1];
    	this.divs_transparentDiv.style.width = bodyWidth + 'px';
    	this.divs_transparentDiv.style.height = bodyHeight + 'px';		
		   	
    }
	// }}}	
	,
	// {{{ __insertContent()
    /**
     *	Insert content into the content div
     * 	
     *
     * @private	
     */	
    __insertContent : function()
    {
		if(this.url){	// url specified - load content dynamically
			ajax_loadContent('DHTMLSuite_modalBox_contentDiv',this.url);
		}else{	// no url set, put static content inside the message box
			this.divs_content.innerHTML = this.htmlOfModalMessage;	
		}
    }		
}

/*******************************************************************/
/*																   */
/*							UTIL MODAL							   */
/*																   */
/*******************************************************************/

messageObj = new DHTML_modalMessage();	// We only create one object of this class
messageObj.setShadowOffset(5);	// Large shadow

function displayMessage(response) {	
	messageObj.setHtmlContent(response);
	messageObj.setCssClassMessageBox(false);
//	messageObj.setSize(width, height);
	messageObj.setShadowDivVisible(false);	// Enable shadow for these boxes
	messageObj.display();
}

function closeMessage() {
	messageObj.close();	
}

/*******************************************************************/
/*                                                                 */
/*                            BOX OVER                             */
/*                                                                 */
/*******************************************************************/


/* --- BoxOver ---
/* --- v 2.1 17th June 2006
By Oliver Bryant with help of Matthew Tagg
http://boxover.swazz.org */

if (typeof document.attachEvent!='undefined') {
   window.attachEvent('onload',init);
   document.attachEvent('onmousemove',moveMouse);
   document.attachEvent('onclick',checkMove); }
else {
   window.addEventListener('load',init,false);
   document.addEventListener('mousemove',moveMouse,false);
   document.addEventListener('click',checkMove,false);
}

var oDv=document.createElement("div");
var dvHdr=document.createElement("div");
var dvBdy=document.createElement("div");
var windowlock,boxMove,fixposx,fixposy,lockX,lockY,fixx,fixy,ox,oy,boxLeft,boxRight,boxTop,boxBottom,evt,mouseX,mouseY,boxOpen,totalScrollTop,totalScrollLeft;
boxOpen=false;
ox=10;
oy=10;
lockX=0;
lockY=0;

function init() {
    oDv.appendChild(dvHdr);
    oDv.appendChild(dvBdy);
    oDv.style.position="absolute";
    oDv.style.visibility='hidden';    
    document.body.appendChild(oDv);    
}

function defHdrStyle() {
    dvHdr.innerHTML='<img  style="vertical-align:middle"  src="info.gif">&nbsp;&nbsp;'+dvHdr.innerHTML;
    dvHdr.style.fontWeight='bold';
    dvHdr.style.width='150px';
    dvHdr.style.fontFamily='arial';
    dvHdr.style.border='1px solid #A5CFE9';
    dvHdr.style.padding='3';
    dvHdr.style.fontSize='11';
    dvHdr.style.color='#4B7A98';
    dvHdr.style.background='#D5EBF9';
    dvHdr.style.filter='alpha(opacity=85)'; // IE
    dvHdr.style.opacity='0.85'; // FF
    //dvBdy.style.zIndex='100001';
}

function defBdyStyle() {
    dvBdy.style.borderBottom='1px solid #A5CFE9';
    dvBdy.style.borderLeft='1px solid #A5CFE9';
    dvBdy.style.borderRight='1px solid #A5CFE9';
    dvBdy.style.width='150px';
    dvBdy.style.fontFamily='arial';
    dvBdy.style.fontSize='11';
    dvBdy.style.padding='3';
    dvBdy.style.color='#1B4966';
    dvBdy.style.background='#EEEEEE';
    dvBdy.style.filter='alpha(opacity=85)'; // IE
    dvBdy.style.opacity='0.85'; // FF
    //dvBdy.style.zIndex='100001';
}

function checkElemBO(txt) {
if (!txt || typeof(txt) != 'string') return false;
if ((txt.indexOf('header')>-1)&&(txt.indexOf('body')>-1)&&(txt.indexOf('[')>-1)&&(txt.indexOf('[')>-1)) 
   return true;
else
   return false;
}

function scanBO(curNode) {
      if (checkElemBO(curNode.title)) {
         curNode.boHDR=getParam('header',curNode.title);
         curNode.boBDY=getParam('body',curNode.title);
            curNode.boCSSBDY=getParam('cssbody',curNode.title);            
            curNode.boCSSHDR=getParam('cssheader',curNode.title);
            curNode.IEbugfix=(getParam('hideselects',curNode.title)=='on')?true:false;
            curNode.fixX=parseInt(getParam('fixedrelx',curNode.title));
            curNode.fixY=parseInt(getParam('fixedrely',curNode.title));
            curNode.absX=parseInt(getParam('fixedabsx',curNode.title));
            curNode.absY=parseInt(getParam('fixedabsy',curNode.title));
            curNode.offY=(getParam('offsety',curNode.title)!='')?parseInt(getParam('offsety',curNode.title)):10;
            curNode.offX=(getParam('offsetx',curNode.title)!='')?parseInt(getParam('offsetx',curNode.title)):10;
            curNode.fade=(getParam('fade',curNode.title)=='on')?true:false;
            curNode.fadespeed=(getParam('fadespeed',curNode.title)!='')?getParam('fadespeed',curNode.title):0.04;
            curNode.delay=(getParam('delay',curNode.title)!='')?parseInt(getParam('delay',curNode.title)):0;
            if (getParam('requireclick',curNode.title)=='on') {
                curNode.requireclick=true;
                document.all?curNode.attachEvent('onclick',showHideBox):curNode.addEventListener('click',showHideBox,false);
                document.all?curNode.attachEvent('onmouseover',hideBox):curNode.addEventListener('mouseover',hideBox,false);
            }
            else {// Note : if requireclick is on the stop clicks are ignored               
               if (getParam('doubleclickstop',curNode.title)!='off') {
                   document.all?curNode.attachEvent('ondblclick',pauseBox):curNode.addEventListener('dblclick',pauseBox,false);
               }    
               if (getParam('singleclickstop',curNode.title)=='on') {
                   document.all?curNode.attachEvent('onclick',pauseBox):curNode.addEventListener('click',pauseBox,false);
               }
           }
            curNode.windowLock=getParam('windowlock',curNode.title).toLowerCase()=='off'?false:true;
            curNode.title='';
            curNode.hasbox=1;
       }
       else
          curNode.hasbox=2;   
}


function getParam(param,list) {
    var reg = new RegExp('([^a-zA-Z]' + param + '|^' + param + ')\\s*=\\s*\\[\\s*(((\\[\\[)|(\\]\\])|([^\\]\\[]))*)\\s*\\]');
    var res = reg.exec(list);
    var returnvar;
    if(res)
        return res[2].replace('[[','[').replace(']]',']');
    else
        return '';
}

function Left(elem){    
    var x=0;
    if (elem.calcLeft)
        return elem.calcLeft;
    var oElem=elem;
    while(elem){
         if ((elem.currentStyle)&& (!isNaN(parseInt(elem.currentStyle.borderLeftWidth)))&&(x!=0))
             x+=parseInt(elem.currentStyle.borderLeftWidth);
         x+=elem.offsetLeft;
         elem=elem.offsetParent;
      } 
    oElem.calcLeft=x;
    return x;
    }

function Top(elem){
     var x=0;
     if (elem.calcTop)
         return elem.calcTop;
     var oElem=elem;
     while(elem){        
          if ((elem.currentStyle)&& (!isNaN(parseInt(elem.currentStyle.borderTopWidth)))&&(x!=0))
             x+=parseInt(elem.currentStyle.borderTopWidth); 
         x+=elem.offsetTop;
             elem=elem.offsetParent;
      } 
      oElem.calcTop=x;
      return x;
      
}

var ah,ab;
function applyStyles() {
    if(ab)
        oDv.removeChild(dvBdy);
    if (ah)
        oDv.removeChild(dvHdr);
    dvHdr=document.createElement("div");
    dvBdy=document.createElement("div");
    CBE.boCSSBDY?dvBdy.className=CBE.boCSSBDY:defBdyStyle();
    CBE.boCSSHDR?dvHdr.className=CBE.boCSSHDR:defHdrStyle();
    dvHdr.innerHTML=CBE.boHDR;
    dvBdy.innerHTML=CBE.boBDY;
    ah=false;
    ab=false;
    if (CBE.boHDR!='') {        
        oDv.appendChild(dvHdr);
        ah=true;
    }    
    if (CBE.boBDY!=''){
        oDv.appendChild(dvBdy);
        ab=true;
    }    
}

var CSE,iterElem,LSE,CBE,LBE, totalScrollLeft, totalScrollTop, width, height ;
var ini=false;

// Customised function for inner window dimension
function SHW() {
   if (document.body && (document.body.clientWidth !=0)) {
      width=document.body.clientWidth;
      height=document.body.clientHeight;
   }
   if (document.documentElement && (document.documentElement.clientWidth!=0) && (document.body.clientWidth + 20 >= document.documentElement.clientWidth)) {
      width=document.documentElement.clientWidth;   
      height=document.documentElement.clientHeight;   
   }   
   return [width,height];
}


var ID=null;
function moveMouse(e) {
   //boxMove=true;
    e?evt=e:evt=event;
    
    CSE=evt.target?evt.target:evt.srcElement;
    
    if (!CSE.hasbox) {
       // Note we need to scan up DOM here, some elements like TR don't get triggered as srcElement
       iElem=CSE;
       while ((iElem.parentNode) && (!iElem.hasbox)) {
          scanBO(iElem);
          iElem=iElem.parentNode;
       }       
    }
    
    if ((CSE!=LSE)&&(!isChild(CSE,dvHdr))&&(!isChild(CSE,dvBdy))){        
       if (!CSE.boxItem) {
            iterElem=CSE;
            while ((iterElem.hasbox==2)&&(iterElem.parentNode))
                    iterElem=iterElem.parentNode; 
            CSE.boxItem=iterElem;
            }
        iterElem=CSE.boxItem;
        if (CSE.boxItem&&(CSE.boxItem.hasbox==1))  {
            LBE=CBE;
            CBE=iterElem;
            if (CBE!=LBE) {
                applyStyles();
                if (!CBE.requireclick)
                    if (CBE.fade) {
                        if (ID!=null)
                            clearTimeout(ID);
                        ID=setTimeout("fadeIn("+CBE.fadespeed+")",CBE.delay);
                    }
                    else {
                        if (ID!=null)
                            clearTimeout(ID);
                        COL=1;
                        ID=setTimeout("oDv.style.visibility='visible';ID=null;",CBE.delay);                        
                    }
                if (CBE.IEbugfix) {hideSelects();} 
                fixposx=!isNaN(CBE.fixX)?Left(CBE)+CBE.fixX:CBE.absX;
                fixposy=!isNaN(CBE.fixY)?Top(CBE)+CBE.fixY:CBE.absY;            
                lockX=0;
                lockY=0;
                boxMove=true;
                ox=CBE.offX?CBE.offX:10;
                oy=CBE.offY?CBE.offY:10;
            }
        }
        else if (!isChild(CSE,dvHdr) && !isChild(CSE,dvBdy) && (boxMove))    {
            // The conditional here fixes flickering between tables cells.
            if ((!isChild(CBE,CSE)) || (CSE.tagName!='TABLE')) {               
               CBE=null;
               if (ID!=null)
                      clearTimeout(ID);
               fadeOut();
               showSelects();
            }
        }
        LSE=CSE;
    }
    else if (((isChild(CSE,dvHdr) || isChild(CSE,dvBdy))&&(boxMove))) {
        totalScrollLeft=0;
        totalScrollTop=0;
        
        iterElem=CSE;
        while(iterElem) {
            if(!isNaN(parseInt(iterElem.scrollTop)))
                totalScrollTop+=parseInt(iterElem.scrollTop);
            if(!isNaN(parseInt(iterElem.scrollLeft)))
                totalScrollLeft+=parseInt(iterElem.scrollLeft);
            iterElem=iterElem.parentNode;            
        }
        if (CBE!=null) {
            boxLeft=Left(CBE)-totalScrollLeft;
            boxRight=parseInt(Left(CBE)+CBE.offsetWidth)-totalScrollLeft;
            boxTop=Top(CBE)-totalScrollTop;
            boxBottom=parseInt(Top(CBE)+CBE.offsetHeight)-totalScrollTop;
            doCheck();
        }
    }
    
    if (boxMove&&CBE) {
        // This added to alleviate bug in IE6 w.r.t DOCTYPE
        bodyScrollTop=document.documentElement&&document.documentElement.scrollTop?document.documentElement.scrollTop:document.body.scrollTop;
        bodyScrollLet=document.documentElement&&document.documentElement.scrollLeft?document.documentElement.scrollLeft:document.body.scrollLeft;
        mouseX=evt.pageX?evt.pageX-bodyScrollLet:evt.clientX-document.body.clientLeft;
        mouseY=evt.pageY?evt.pageY-bodyScrollTop:evt.clientY-document.body.clientTop;
        if ((CBE)&&(CBE.windowLock)) {
            mouseY < -oy?lockY=-mouseY-oy:lockY=0;
            mouseX < -ox?lockX=-mouseX-ox:lockX=0;
            mouseY > (SHW()[1]-oDv.offsetHeight-oy)?lockY=-mouseY+SHW()[1]-oDv.offsetHeight-oy:lockY=lockY;
            mouseX > (SHW()[0]-dvBdy.offsetWidth-ox)?lockX=-mouseX-ox+SHW()[0]-dvBdy.offsetWidth:lockX=lockX;            
        }
        oDv.style.left=((fixposx)||(fixposx==0))?fixposx:bodyScrollLet+mouseX+ox+lockX+"px";
        oDv.style.top=((fixposy)||(fixposy==0))?fixposy:bodyScrollTop+mouseY+oy+lockY+"px";        
        
    }
}

function doCheck() {    
    if (   (mouseX < boxLeft)    ||     (mouseX >boxRight)     || (mouseY < boxTop) || (mouseY > boxBottom)) {
        if (!CBE.requireclick)
            fadeOut();
        if (CBE.IEbugfix) {showSelects();}
        CBE=null;
    }
}

function pauseBox(e) {
   e?evt=e:evt=event;
    boxMove=false;
    evt.cancelBubble=true;
}

function showHideBox(e) {
    oDv.style.visibility=(oDv.style.visibility!='visible')?'visible':'hidden';
}

function hideBox(e) {
    oDv.style.visibility='hidden';
}

var COL=0;
var stopfade=false;
function fadeIn(fs) {
        ID=null;
        COL=0;
        oDv.style.visibility='visible';
        fadeIn2(fs);
}

function fadeIn2(fs) {
        COL=COL+fs;
        COL=(COL>1)?1:COL;
        oDv.style.filter='alpha(opacity='+parseInt(100*COL)+')';
        oDv.style.opacity=COL;
        if (COL<1)
         setTimeout("fadeIn2("+fs+")",20);        
}


function fadeOut() {
    oDv.style.visibility='hidden';
    
}

function isChild(s,d) {
    while(s) {
        if (s==d) 
            return true;
        s=s.parentNode;
    }
    return false;
}

var cSrc;
function checkMove(e) {
    e?evt=e:evt=event;
    cSrc=evt.target?evt.target:evt.srcElement;
    if ((!boxMove)&&(!isChild(cSrc,oDv))) {
        fadeOut();
        if (CBE&&CBE.IEbugfix) {showSelects();}
        boxMove=true;
        CBE=null;
    }
}

function showSelects(){
   var elements = document.getElementsByTagName("select");
   for (i=0;i< elements.length;i++){
      elements[i].style.visibility='visible';
   }
}

function hideSelects(){
   var elements = document.getElementsByTagName("select");
   for (i=0;i< elements.length;i++){
   elements[i].style.visibility='hidden';
   }
}

function getDateFromText(text) {
	// TODO: Internationalization of the date
	var temp = new Array();
	temp = text.split('-');
	var date = new Date();
	date.setFullYear(temp[2], temp[1]-1, temp[0]);
	return date;
}

function onEnter(event, functoeval) {	
	if (event.keyCode == 13) {
		if (functoeval == 'comenzi') show_comenzi('pag_and_content', 0);
		if (functoeval == 'firme') show_firme('content_firme', 0);
		if (functoeval == 'cauta_contacte') cauta_contact(0);
		if (functoeval == 'cauta_comanda_avansata') new_cauta_confirm();
	}
}

function show_modal_firma_from_comanda(span_id_combobox_from1, span_id_combobox_from2, Width, Height, action, combobox_id) {

	if (action == 'add') {
		sndReqNew('modal_add_firma_from_comanda.php','from='+combobox_id+'&raspuns_final_id1='+span_id_combobox_from1+'&raspuns_final_id2='+span_id_combobox_from2,'', 'displayMessage(response); document.getElementById(\'nume_firma_modal\').focus();', 0);		
	}
	else {
		//editare firma in modal
		var firma_comanda = document.getElementById(combobox_id);
		var firma_comanda_id = firma_comanda.options[firma_comanda.selectedIndex].value;	
		sndReqNew('modal_add_firma_from_comanda.php','from='+combobox_id+'&raspuns_final_id1='+span_id_combobox_from1+'&raspuns_final_id2='+span_id_combobox_from2+'&index='+firma_comanda_id,'', 'displayMessage(response); document.getElementById(\'nume_firma_modal\').focus();', 0);
	}	
}

function render_firme_ajax1(from, id_final, index) {
	if (from == 'id_firma_exec') 
		sndReqNew('AJAX_proxy.php', 'from='+from+'&f=render_firme_add_comanda_combobox&index='+index, id_final, 'arata_contacte_comanda(-1,\'contact_sol\');', 0);
	else {
		sndReqNew('AJAX_proxy.php', 'from='+from+'&f=render_firme_add_comanda_combobox&index='+index, id_final, 'arata_contacte_comanda(-1,\'contact_exec\');', 0);
	}		
}

function render_firme_ajax2(from, id_final, index) {	
	if (from == 'id_firma_exec') 
		sndReqNew('AJAX_proxy.php', 'from='+from+'&f=render_firme_add_comanda_combobox&index='+index, id_final, '', 0);
	else
		sndReqNew('AJAX_proxy.php', 'from='+from+'&f=render_firme_add_comanda_combobox&index='+index, id_final, '', 0);
}

function render_firme_adaugate_modal(index, id_final1, id_final2, from) {
	if (index == -1) {
		//adaugare
		if (from == 'id_firma_sol') {
			//pastrez valoarea selectata din id_firma_exec
			var firma_comanda = document.getElementById('id_firma_exec');
			var index = firma_comanda.options[firma_comanda.selectedIndex].value;				 
			sndReqNew('AJAX_proxy.php', 'from=id_firma_sol&f=render_firme_add_comanda_combobox&index=desc', id_final1, 'render_firme_ajax1(\'id_firma_exec\',\''+id_final2+'\','+index+');', 0);
			
		}					
		else {
			//pastrez valoarea selectata din id_firma_sol
			var firma_comanda = document.getElementById('id_firma_sol');
			var index = firma_comanda.options[firma_comanda.selectedIndex].value;				 					
			sndReqNew('AJAX_proxy.php', 'index=desc&from=id_firma_exec&f=render_firme_add_comanda_combobox', id_final2, 'render_firme_ajax1(\'id_firma_sol\',\''+id_final1+'\','+index+');', 0);
		}		
	}
	else {		
		//editare		
		if (from == 'id_firma_sol') {
			//pastrez valoarea selectata din id_firma_exec
			var firma_comanda = document.getElementById('id_firma_exec');
			var index2 = firma_comanda.options[firma_comanda.selectedIndex].value;				 				
			sndReqNew('AJAX_proxy.php', 'from=id_firma_sol&f=render_firme_add_comanda_combobox&index='+index, id_final1, 'render_firme_ajax2(\'id_firma_exec\',\''+id_final2+'\','+index2+');', 0);
			
		}			
		else {
			//pastrez valoarea selectata din id_firma_exec
			var firma_comanda = document.getElementById('id_firma_sol');
			var index2 = firma_comanda.options[firma_comanda.selectedIndex].value;				 		
			sndReqNew('AJAX_proxy.php', 'from=id_firma_sol&f=render_firme_add_comanda_combobox&index='+index2, id_final1, 'render_firme_ajax2(\'id_firma_exec\',\''+id_final2+'\','+index+');', 0);
		}
	}
}


function render_contacte_ajax_in_comanda(id_where_to_render, index, id_firma) {
	var from = "id_" + id_where_to_render;
	sndReqNew('AJAX_proxy.php', 'id_firma='+id_firma+'&from='+from+'&f=render_contacte_add_comanda_combobox&index='+index, id_where_to_render, '', 0);
}

function render_contacte_adaugate_modal(index, id_final, from, id_firma) {
	if (index == -1) {
		//adaugare
		
		if (from == 'id_contact_sol') {			
			var firma_comanda = document.getElementById('id_firma_exec');
			var firma_exec_id = firma_comanda.options[firma_comanda.selectedIndex].value;
			//daca id_firma == firma_exec_id va trebui sa rerandez conctele la executant.. daca nu, NU
			if (id_firma == firma_exec_id) {	
				
				//trebuie pastrat id-ul contactului selectat la executant
				var contact_exec_sel = document.getElementById('id_contact_exec');
				var index_exec = contact_exec_sel.options[contact_exec_sel.selectedIndex].value;							 
				sndReqNew('AJAX_proxy.php', 'id_firma='+id_firma+'&from=id_contact_sol&f=render_contacte_add_comanda_combobox&index=desc', id_final, 'render_contacte_ajax_in_comanda(\'contact_exec\','+index_exec+','+id_firma+');', 0);
			}
			else 
				sndReqNew('AJAX_proxy.php', 'id_firma='+id_firma+'&from=id_contact_sol&f=render_contacte_add_comanda_combobox&index=desc', id_final, '', 0);				
		}					
		else {
			var firma_comanda = document.getElementById('id_firma_sol');
			var firma_sol_id = firma_comanda.options[firma_comanda.selectedIndex].value;
			//daca id_firma == firma_exec_id va trebui sa rerandez conctele la executant.. daca nu, NU
			if (id_firma == firma_sol_id) {	
				//trebuie pastrat id-ul contactului selectat la executant
				var contact_sol_sel = document.getElementById('id_contact_sol');
				var index_sol = contact_sol_sel.options[contact_sol_sel.selectedIndex].value;							 
				sndReqNew('AJAX_proxy.php', 'id_firma='+id_firma+'&from=id_contact_exec&f=render_contacte_add_comanda_combobox&index=desc', id_final, 'render_contacte_ajax_in_comanda(\'contact_sol\','+index_sol+','+id_firma+');', 0);
			}
			else 
				sndReqNew('AJAX_proxy.php', 'id_firma='+id_firma+'&from=id_contact_exec&f=render_contacte_add_comanda_combobox&index=desc', id_final, '', 0);				
		}		
	}
	else {		
		//editare		
							
		var firma_comanda = document.getElementById('id_firma_exec');
		var firma_exec_id = firma_comanda.options[firma_comanda.selectedIndex].value;

		var firma_comanda = document.getElementById('id_firma_sol');
		var firma_sol_id = firma_comanda.options[firma_comanda.selectedIndex].value;

		//daca id_firma == firma_exec_id va trebui sa rerandez conctele la executant.. daca nu, NU

		var contact_exec_sel = document.getElementById('id_contact_exec');
		var index_exec = contact_exec_sel.options[contact_exec_sel.selectedIndex].value;

		var contact_sol_sel = document.getElementById('id_contact_sol');
		var index_sol = contact_sol_sel.options[contact_sol_sel.selectedIndex].value;	
		
		if (from == 'id_contact_sol') {						 			
			if (id_firma == firma_exec_id) {															
				sndReqNew('AJAX_proxy.php', 'id_firma='+id_firma+'&from=id_contact_sol&f=render_contacte_add_comanda_combobox&index='+index_sol, id_final, 'render_contacte_ajax_in_comanda(\'contact_exec\','+index_exec+','+id_firma+');', 0);
			}
			else 
				sndReqNew('AJAX_proxy.php', 'id_firma='+id_firma+'&from=id_contact_sol&f=render_contacte_add_comanda_combobox&index='+index_sol, id_final, '', 0);							
		}			
		else {
			if (id_firma == firma_sol_id) {															
				sndReqNew('AJAX_proxy.php', 'id_firma='+id_firma+'&from=id_contact_exec&f=render_contacte_add_comanda_combobox&index='+index_exec, id_final, 'render_contacte_ajax_in_comanda(\'contact_sol\','+index_sol+','+id_firma+');', 0);
			}
			else {
				sndReqNew('AJAX_proxy.php', 'id_firma='+id_firma+'&from=id_contact_exec&f=render_contacte_add_comanda_combobox&index='+index_exec, id_final, '', 0);
			}							
		}
	}
}

function new_firma_confirm(from, optiune, index, id_final1, id_final2) {
	var nume_firma = document.getElementById('nume_firma_modal').value;
	var tel_fix = document.getElementById('tel_fix_modal').value;
	var tel_fax = document.getElementById('tel_fax_modal').value;	
	var tel_mobil = document.getElementById('tel_mobil_modal').value;
	var email_modal = document.getElementById('email_modal').value;
	
	document.getElementById('td_nume_firma_modal').className = '';
    document.getElementById('td_tel_fix_modal').className = '';
    document.getElementById('td_tel_fax_modal').className = '';
    document.getElementById('td_email_modal').className = '';
    
    //submit the data to the server

	sndReqNew('AJAX_proxy.php', 'f=ajax_create_new_firma_from_modal&optiune='+optiune+'&index='+index+'&nume_firma='+nume_firma+'&tel_fix='+tel_fix+'&tel_fax='+tel_fax+'&tel_mobil='+tel_mobil+'&email_modal='+email_modal, '', 'closeMessage(); render_firme_adaugate_modal('+index+',\''+id_final1+'\',\''+id_final2+'\',\''+from+'\');', 0);
}

function show_modal_contact_from_comanda(span_id_combobox_from, Width, Height, action, combobox_id) {

	//trebuie sa pastrez id-ul firmei careia ii se va adauga noul contact
	if (combobox_id == 'id_contact_sol') {
		var firma_sel = document.getElementById('id_firma_sol');
		var firma_id = firma_sel.options[firma_sel.selectedIndex].value;		
	}
	else {
		var firma_sel = document.getElementById('id_firma_exec');
		var firma_id = firma_sel.options[firma_sel.selectedIndex].value;		
	}
	
	if (action == 'add') {
		sndReqNew('modal_add_contact_firma_from_comanda.php','firma_id='+firma_id+'&from='+combobox_id+'&raspuns_final_id='+span_id_combobox_from,'', 'displayMessage(response); document.getElementById(\'contact_nume\').focus();', 0);		
	}
	else {
		//editare contact in modal
		var contact_comanda = document.getElementById(combobox_id);
		var contact_comanda_id = contact_comanda.options[contact_comanda.selectedIndex].value;
			
		sndReqNew('modal_add_contact_firma_from_comanda.php','index='+contact_comanda_id+'&firma_id='+firma_id+'&from='+combobox_id+'&raspuns_final_id='+span_id_combobox_from, '', 'displayMessage(response); document.getElementById(\'contact_nume\').focus();', 0);
	}	
}

function new_contact_from_comanda_confirm(from, optiune, index, id_final, id_firma) {
	
	var nume_contact = document.getElementById('contact_nume').value;
	
	var contact_sex_sel = document.getElementById('contact_sex');
	var contact_sex = contact_sex_sel.options[contact_sex_sel.selectedIndex].value;	
			
	var tel_fix = document.getElementById('contact_tel_fix').value;	
	var email = document.getElementById('contact_email').value;
	
	document.getElementById('td_contact_nume').className = '';
    document.getElementById('td_contact_sex').className = '';
    document.getElementById('td_contact_tel_fix').className = '';
    document.getElementById('td_contact_email').className = '';
    
    //submit the data to the server

	sndReqNew('AJAX_proxy.php', 'id_firma='+id_firma+'&f=ajax_create_new_contact_from_modal&optiune='+optiune+'&index='+index+'&nume_contact='+nume_contact+'&contact_sex='+contact_sex+'&tel_fix='+tel_fix+'&email='+email, '', 'closeMessage(); render_contacte_adaugate_modal('+index+',\''+id_final+'\',\''+from+'\','+id_firma+');', 0);
}

function selecteaza_toate_checkboxes(tot_nimic) {
	var node_list = document.getElementsByTagName('input');
	var contor = 0;
	if (tot_nimic == 1) {
		//trebuie selectate toate comenziile     
		
   		for (var i = 0; i < node_list.length; i++) {
   			var node = node_list[i];  
			if (node.getAttribute('type') == 'checkbox') {
				comenzi_indici[contor] = node.value;
				contor++;
				node.checked = true;				
   			}
  		} 
  		set_comenzi_row();
	}
	else {
		//nici o comanda selectata
		comenzi_indici.length = 0;
		comenzi_indici = [];		
   		for (var i = 0; i < node_list.length; i++) {
   			var node = node_list[i];  
			if (node.getAttribute('type') == 'checkbox') {
				node.checked = false;				
   			}
  		} 	
  		set_comenzi_row();	
	}
}

function select_all_checkboxes_firms(tot_nimic) {
	var node_list = document.getElementsByTagName('input');
	var contor = 0;
	if (tot_nimic == 1) {		     		
   		for (var i = 0; i < node_list.length; i++) {
   			var node = node_list[i];  
			if (node.getAttribute('type') == 'checkbox') {
				node.checked = true;	
				firme_indici[contor] = node.value;
				contor++;							
   			}
  		} 
  		set_firme_row();
	}
	else {
		firme_indici.length = 0;
		firme_indici = [];		
   		for (var i = 0; i < node_list.length; i++) {
   			var node = node_list[i];  
			if (node.getAttribute('type') == 'checkbox') {
				node.checked = false;				
   			}
  		} 	
  		set_firme_row();	
	}
}

function show_modal_add_dashboard(tip, index) {
	sndReqNew('modal_add_dashboard.php','index='+index+'&tip='+tip,'', 'displayMessage(response); document.getElementById(\'tara_plecare\').focus();', 0);
}

function delete_dash(dashboard_id, tip) {
	if (confirm(LANG_Vreti_sa_stergeti_din_dashboard)) {	
		if (tip == CT_DASHBOARD_MARFA) 
			var td_id = 'dash_marfa'
		else
			var td_id = 'dash_camion';
		sndReqNew('AJAX_proxy.php', 'tip='+tip+'&f=ajax_delete_render_dash&id='+dashboard_id, td_id, '', 0);
	}
}

function dash_to_order(dash_id) {
	document.location = 'add_comanda.php?dash_id=' + dash_id;
}

function show_modal_confirma_incarcare_descarcare(id_adresa, id_comanda, tip_adresa, id_lista) {
    sndReqNew('modal_confirma_incarcare_descarcare.php','id_adresa='+id_adresa+'&id_comanda='
                +id_comanda+'&tip_adresa='+tip_adresa+'&id_lista='+id_lista,'', 'displayMessage(response);', 1);
}

function date_confirm(id_adresa, id_comanda, id_lista, tip_adresa) {
    var data_efectiva = document.getElementById('data_efectiva').value;
    
    document.getElementById('td_data_efectiva').className = '';
    
    //submit the data to the server

    sndReqNew('AJAX_proxy.php', 'f=ajax_date_confirm&id_adresa='+id_adresa+'&id_comanda='+id_comanda+'&data_efectiva='+data_efectiva
    , '', 'closeMessage(); render_incarcari_descarcari_urgente('+tip_adresa+',\''+id_lista+'\');', 0);
}

function render_incarcari_descarcari_urgente(tip_adresa, id_lista) {
    sndReqNew('AJAX_proxy.php', 'f=render_incarcari_descarcari_urgente&tip_adresa='+tip_adresa+'&id_lista='+id_lista, id_lista, '', 0);
}